【问题标题】:SQL Code to get Week Number when week begins Sunday to Saturday星期天到星期六开始时获取周数的 SQL 代码
【发布时间】:2021-12-31 16:31:27
【问题描述】:

我公司的一周从星期日开始。 我遇到的问题是从数据库中的日期中提取周数。

例如,使用星期日周开始逻辑,02/01/2022 落在 2021 年的第 52 周。怎么写SQL代码给我:

a) 周数(即 2022 年 1 月 2 日是第 52 周的一部分)

b) 一周中正确的年份。即 2022 年 1 月 2 日,我希望它带回“2021”年,以便我的数据集完整且准确。

注意 我使用的数据库名称是 dw-fin,日期的列称为 date-created

【问题讨论】:

  • 请分享您迄今为止可能尝试过的任何代码。
  • 您阅读过 WEEK() 函数的文档吗?

标签: mysql sql


【解决方案1】:

您可以将WEEK 函数与“模式”一起使用。
这是一个整数,表示一周的开始。
YEARWEEK函数也有模式。

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

例子:

select date_column
, month(date_column) as month
, year(date_column) as year
, yearweek(date_column, 2) as mode2_yearweek
, floor(yearweek(date_column, 2)/100) as mode2_year
, week(date_column, 2) as mode2_week
from (select date('2022-01-01') as date_column) q;
date_column month year mode2_yearweek mode2_year mode2_week
2022-01-01 1 2022 202152 2021 52

dbfiddle here

上的演示

【讨论】:

    猜你喜欢
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多