我試圖增加一週號碼,以便在今年的週數將不重複增量週數在SQL Server
例如18/12/2016爲週數51,25/12/2016爲一週編號52和01/01/2017是周編號1,08/01/2017是周編號2。
我想要的是2016年12月18日week NO 51,25/12/2016 week No 52,week 53號,2017年8月1日一週號54等,以便沒有周將重複
見我的數據集和查詢的樣本我已經試過
DECLARE @Table1 table (Week_End_Date DATE)
INSERT INTO @Table1
VALUES ('2016-04-03'), ('2016-04-10'), ('2016-04-17'), ('2016-04-24'),
('2016-05-01'), ('2016-05-08'), ('2016-05-15'), ('2016-05-22'),
('2016-05-29'), ('2016-06-05'), ('2016-06-12'), ('2016-06-19'),
('2016-06-26'), ('2016-07-03'), ('2016-07-10'), ('2016-07-17'),
('2016-07-24'), ('2016-07-31'), ('2016-08-07'), ('2016-08-14'),
('2016-08-21'), ('2016-08-28'), ('2016-09-04'), ('2016-09-11'),
('2016-09-18'), ('2016-09-25'), ('2016-10-02'), ('2016-10-09'),
('2016-10-16'), ('2016-10-23'), ('2016-10-30'), ('2016-11-06'),
('2016-11-13'), ('2016-11-20'), ('2016-11-27'), ('2016-12-04'),
('2016-12-11'), ('2016-12-18'), ('2016-12-25'), ('2017-01-01'),
('2017-01-08'), ('2017-01-15'), ('2017-01-22'), ('2017-01-29'),
('2017-02-05'), ('2017-02-12'), ('2017-02-19'), ('2017-02-26'),
('2017-03-05'), ('2017-03-12'), ('2017-03-19'), ('2017-03-26'),
('2017-04-02'), ('2017-04-09'), ('2017-04-16'), ('2017-04-23'),
('2017-04-30'), ('2017-05-07'), ('2017-05-14'), ('2017-05-21'),
('2017-05-28'), ('2017-06-04'), ('2017-06-11'), ('2017-06-18'),
('2017-06-25'), ('2017-07-02'), ('2017-07-09'), ('2017-07-16'),
('2017-07-23'), ('2017-07-30'), ('2017-08-06'), ('2017-08-13'),
('2017-08-20'), ('2017-08-27'), ('2017-09-03'), ('2017-09-10'),
('2017-09-17'), ('2017-09-24'), ('2017-10-01'), ('2017-10-08'),
('2017-10-15'), ('2017-10-22'), ('2017-10-29'), ('2017-11-05'),
('2017-11-12'), ('2017-11-19'), ('2017-11-26'), ('2017-12-03'),
('2017-12-10'), ('2017-12-17'), ('2017-12-24'), ('2017-12-31'),
('2018-01-07'), ('2018-01-14'), ('2018-01-21'), ('2018-01-28'),
('2018-02-04'), ('2018-02-11'), ('2018-02-18'), ('2018-02-25'),
('2018-03-04'), ('2018-03-11'), ('2018-03-18'), ('2018-03-25'),
('2018-04-01')
查詢:
SELECT
Week_End_Date,
DATEPART(WEEK,Week_End_Date) AS WeekNumber,
REPLACE(LEFT(Week_End_Date,7),'-','') +
CASE
WHEN CAST(DATEPART(WEEK, Week_End_Date) AS VARCHAR(2)) IN ('1', '2', '3', '4', '5', '6', '7', '8', '9')
THEN '0' + CAST(DATEPART(WEEK, Week_End_Date) AS VARCHAR(2))
ELSE CAST(DATEPART(WEEK, Week_End_Date) AS VARCHAR(2))
END Wk_NO_Norepeat
FROM
@Table1
ORDER BY
Week_End_Date
所需的輸出
Date Current week number Expected output
04/12/2016 49 49
11/12/2016 50 50
18/12/2016 51 51
25/12/2016 52 52
01/01/2017 1 53
08/01/2017 2 54
15/01/2017 3 55
22/01/2017 4 56
29/01/2017 5 57