我从下面的Stack question上的已批准答案中借用了一个查询建议,以计算给定IW周数的日期范围。在将一些语法合并到我自己的查询中后,我创建了以下SQL:
SELECT
t.termination_date,
to_char(t.termination_date,'IW') IW_WEEK,
next_day(to_date( to_char(t.termination_date,'IW') *7, 'DDD')-8, 'mon') WEEK_START_DATE,
next_day(to_date( to_char(t.termination_date,'IW') *7, 'DDD'), 'sun') WEEK_END_DATE
FROM
table t
字符串
我注意到的是,这些周范围只返回2023年的周范围,尽管termination_date是在不同的年份。我不确定这是由next_day()函数的设计引起的,还是某种将IW Week转换为当前年份的内置行为,但我无法找到支持这一点的信息。
我想做的是取一个给定的日期(在我的例子中是终止日期),并计算该日期发生的年份中IW周数的日期范围。
的数据
1条答案
按热度按时间zysjyyx41#
您似乎只想使用
TRUNC(date_column , 'IW')
来获取一周的开始(星期一),然后添加6天来获取星期日。如果你想从ISO年和ISO周计算周的开始和结束日期,那么从ISO年的1月4日开始(因为这总是在第一个ISO周),然后截断到ISO周的开始,并添加7天的倍数以获得正确的ISO周:
字符串
其中,对于样本数据:
型
产出:
| 验证日期|IW_周|周开始日期|周结束日期|WEEK_START_DATE2| WEEK_END_DATE2|
| --|--|--|--|--|--|
| 2019 -01- 27 00:00:00| 01 |2019 -01- 23 00:00:00| 2022-01-09 00:00:00| 2019 -01- 23 00:00:00| 2022-01-09 00:00:00|
| 2019 -01- 18 00:00:00| 01 |2019 -01- 23 00:00:00| 2022-01-09 00:00:00| 2019 -01- 23 00:00:00| 2022-01-09 00:00:00|
| 2022-01-09 00:00:00| 01 |2019 -01- 23 00:00:00| 2022-01-09 00:00:00| 2019 -01- 23 00:00:00| 2022-01-09 00:00:00|
| 2022-01-10 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2022-01-11 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2019 -01-12 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2022-01-13 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2022-01-14 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2022-01-15 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2022-01-16 00:00:00| 02 |2022-01-10 00:00:00| 2022-01-16 00:00:00| 2022-01-10 00:00:00| 2022-01-16 00:00:00|
| 2022-01-17 00:00:00| 03 |2022-01-17 00:00:00| 2019 -01-23 00:00:00| 2022-01-17 00:00:00| 2019 -01-23 00:00:00|
| 2019 -01-18 00:00:00| 03 |2022-01-17 00:00:00| 2019 -01-23 00:00:00| 2022-01-17 00:00:00| 2019 -01-23 00:00:00|
| 2022-01-19 00:00:00| 03 |2022-01-17 00:00:00| 2019 -01-23 00:00:00| 2022-01-17 00:00:00| 2019 -01-23 00:00:00|
| 2019 -01-20 00:00:00| 03 |2022-01-17 00:00:00| 2019 -01-23 00:00:00| 2022-01-17 00:00:00| 2019 -01-23 00:00:00|
| 2019 -01-21 00:00:00| 03 |2022-01-17 00:00:00| 2019 -01-23 00:00:00| 2022-01-17 00:00:00| 2019 -01-23 00:00:00|
fiddle