使用Sql按月和每月的星期细分日期

时间:2020-03-19 18:30:14

标签: sql sql-server

我需要的是按月和该月的星期细分日期。例如,对于'2020-01-06'我想看到January, 1 week,对于'2020-01-13'我想看到January, 2nd week。 这是写的代码:

.....
distinct t1.incidentid
,t1.status as [CW_Staus],
t1.title
,t1.createddatetime
,datename(MM,t1.createddatetime) as Month
,datename(ww,t1.createddatetime) as Week
.....

现在,我看到的是 enter image description here

但是,从每个月初开始,我想重新开始周数。对于'2020-02-01',我想看Feb, 1week。 我在代码中缺少什么? 谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试将月份中的某天除以7:

SELECT DISTINCT
    t1.incidentid,
    t1.status AS [CW_Staus],
    t1.title,
    t1.createddatetime,
    DATENAME(MM, t1.createddatetime) AS Month,
    1 + ((DATEPART(day, t1.createddatetime)-1) / 7) AS WeekOfMonth
...

请记住,以上逻辑假定您实际上想在每个月初重置每个月的周数。通常,有一些ISO标准方法可以计算一年中的星期。需要考虑一些极端情况,因为任何一年的时间可能都不是整个星期。