我有一个日期列表。我想插入整数:从第一个星期一到星期日1,从第二个星期一到星期日2等等......
如何在SQL Server中执行此操作?
预期产出:
03/14/16 1
03/15/16 1
03/16/16 1
03/17/16 1
03/18/16 1
03/19/16 1
03/20/16 1
03/21/16 2
03/22/16 2
03/23/16 2
03/24/16 2
03/25/16 2
03/26/16 2
03/27/16 2
03/28/16 3
03/29/16 3
03/30/16 3
03/31/16 3
04/01/16 3
04/02/16 3
04/03/16 3
04/04/16 4
答案 0 :(得分:2)
试试这个
SELECT DENSE_RANK() OVER( ORDER BY DATEPART(YEAR,[date column])
,DATEPART(WEEK,[date column]) ) FROM table
答案 1 :(得分:1)
与DENSE_RANK
如果您的语言环境没有星期一作为一周的第一天,您可能还需要SET DATEFIRST 1
。
SELECT
MyDate,
DATENAME(WEEKDAY, MyDate),
(DATEPART(WEEK, MyDate) - DATEPART(WEEK,MIN(MyDate) OVER (ORDER BY MyDate)))
+ ((DATEPART(YEAR, MyDate) - DATEPART(YEAR,MIN(MyDate) OVER (ORDER BY MyDate))) *52) + 1 MyWeek
FROM MyData
MyDate MyWeek
---------- ------------------------------ -----------
2015-12-26 Saturday 1
2015-12-27 Sunday 1
2015-12-28 Monday 2
2015-12-29 Tuesday 2
2015-12-30 Wednesday 2
2015-12-31 Thursday 2
2016-01-01 Friday 2
2016-01-02 Saturday 2
2016-01-03 Sunday 2
2016-01-04 Monday 3
2016-01-05 Tuesday 3
修改修复年份
编辑2 真正修复年度越过,每个星期一的增量计数器(例如,如果第一个日期是星期几),请参阅示例数据。
答案 2 :(得分:1)
DECLARE @start DATE = '2016-03-14'
;WITH cte AS (
SELECT @start as [d],
1 as [w]
UNION ALL
SELECT DATEADD(day,1,[d]),
CASE WHEN DATEPART(WEEK,[d]) != DATEPART(WEEK,DATEADD(day,1,[d])) THEN w+1 ELSE w END
FROM cte
WHERE d < '2017-04-04')
SELECT [d], [w]
FROM cte
OPTION (MAXRECURSION 1000)