【问题标题】:SQL - Insert dates in a field between a date rangeSQL - 在日期范围之间的字段中插入日期
【发布时间】:2021-12-17 17:21:22
【问题描述】:

我正在尝试在2021 和 2023 之间的每个 7 days 字段中插入一个 date 这是为了我不要手动插入几次。我在堆栈中找不到任何相关的帖子,所以我决定问一下,因为我真的需要这个任务。

感谢您的回答或任何可能帮助我解决此问题的参考。

编辑:我的错,是amazon redshift

【问题讨论】:

  • 你的错,确实。您标记了错误的数据库。
  • @TimBiegeleisen 谢谢!我能够使用您的演示获得正确的价值。做了一些调整以匹配 postgre 的语法。

标签: sql date datetime amazon-redshift sql-insert


【解决方案1】:
declare @startDate date
declare @endDate date
set @startDate='2021-03-01' -- YYYY-MM-DD format
set @endDate='2023-04-01'

;with all_date as (
    select @startDate Dates
    union all
    select DATEADD(day, 7, Dates)
    from all_date
    where Dates < @endDate
)
INSERT INTO [Table_name]([column])
select Dates from all_date

你可以这样使用...

【解决方案2】:

感谢Tim Biegeleisen 的回答,但不幸的是我说我使用的是MySQL 而不是Amazon Redshift,他删除了他的回答。那是我的一个错误。 我调整了他的答案,并能够生成我需要的正确日期。

select * from 
(select cast(DATEADD(day, 7*(t4*10000 + t3*1000 + t2*100 + t1*10 + t0), '2022-01-03') as date) wk_start from
 (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where wk_start < '2024-01-03'
order by wk_start

我添加了cast 只是为了删除格式中的hours,min,secs。这样我就可以将结果插入到我的表中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多