clickhouse周toWeek函数

toWeek(date[,mode])

返回Date或DateTime的周数。两个参数形式可以指定星期是从星期日还是星期一开始,以及返回值应在0到53还是从1到53的范围内。如果省略了mode参数,则默认 模式为0。

Mode First day of week Range Week 1 is the first week …
0 Sunday 0-53 with a Sunday in this year
1 Monday 0-53 with 4 or more days this year
2 Sunday 1-53 with a Sunday in this year
3 Monday 1-53 with 4 or more days this year
4 Sunday 0-53 with 4 or more days this year
5 Monday 0-53 with a Monday in this year
6 Sunday 1-53 with 4 or more days this year
7 Monday 1-53 with a Monday in this year
8 Sunday 1-53 contains January 1
9 Monday 1-53 contains January 1

这张图用来方便下面的测试
1月1号日历

模式0 默认模式:
一周的第一天是周日,第一周是今年第一个有周日的周

toWeek(toDate('2020-01-01'), 0) 为0, toYearWeek(toDate('2020-01-01'), 0) 为201952  
toWeek(toDate('2020-01-05'), 0) 为1, toYearWeek(toDate('2020-01-05'), 0) 为202001  

模式1:
一周的第一天是周一,第一周是今年第一个有4天或4天以上的周,第一周之前的今年的日期为第0周

toWeek(toDate('2020-01-01'), 1) 为1
toWeek(toDate('2021-01-01'), 1) 为0, toYearWeek(toDate('2021-01-01'), 1) 为202053

模式3:
一周的第一天是周一,第一周是今年第一个有4天或4天以上的周,第一周之前的今年的日期为上一年的第52/53周,即最后一周

toWeek(toDate('2020-01-01'), 3) 为1
toWeek(toDate('2021-01-01'), 3) 为53(上一年最后一周), toYearWeek(toDate('2021-01-01'), 3) 为202053
toWeek(toDate('2022-01-01'), 3) 为52(上一年最后一周), toYearWeek(toDate('2022-01-01'), 3) 为202152

模式5:
一周的第一天是周一,第一周是今年第一个有星期一的周,第一周之前的今年的日期为第0周

toWeek(toDate('2020-01-01'), 5) 为0
toWeek(toDate('2024-01-01'), 5) 为1

模式7:
一周的第一天是周一,第一周是今年第一个有星期一的周,第一周之前的今年的日期为上一年的第52或53周,即最后一周

toWeek(toDate('2019-01-01'), 7) 为53, toYearWeek(toDate('2019-01-01'), 7) 为 201853
toWeek(toDate('2020-01-01'), 7) 为52, toYearWeek(toDate('2020-01-01'), 7) 为 201952
toWeek(toDate('2024-01-01'), 7) 为1

模式9:
一周的第一天是周一,第一周是第一个包含1月1日的周,第一周中的去年的日期也算作今年的第1周

toWeek(toDate('2019-12-29'), 9) 为52
toWeek(toDate('2019-12-30'), 9) 为1
toWeek(toDate('2019-12-31'), 9) 为1 
toWeek(toDate('2020-01-01'), 9) 为1

toYearWeek(date[,mode])

返回Date的年和周。 结果中的年份可能因为Date为该年份的第一周和最后一周而与Date的年份不同。
mode参数的工作方式与toWeek()的mode参数完全相同。 对于单参数语法,mode使用默认值0。

如果toWeek()返回为0, 那么toYearWeek()返回的周为去年的最后一周  
toWeek(toDate('2020-01-01'), 0) 为0, toYearWeek(toDate('2020-01-01'), 0) 为201952

toStartOfWeek(t[,mode])

按mode将Date或DateTime向前取整到最近的星期日或星期一。 返回Date类型。 mode参数的工作方式与toWeek()的mode参数完全相同。 对于单参数语法,mode使用默认值0。

toStartOfWeek(toDate('2021-01-10 12:00:30'), 7) 为 2021-01-04

参考

ClickHouse时间日期函数
https://clickhouse.com/docs/zh/sql-reference/functions/date-time-functions#toweek

posted @ 2023-09-01 16:48  theSummerDay  阅读(715)  评论(0编辑  收藏  举报