ผมเอามาจาก Internet (www.SqlCentral.com) ผมเพียงแค่เก็บรวบรวมเอาไว้ (กันลืม)
Code (SQL)
SET DATEFIRST 7 -- Sunday
SELECT @@DATEFIRST
SET DATEFIRST 1 -- Monday
DECLARE @startDate DATE = '2014-01-01', @endDate DATE = '2014-12-31';
--CROSS JOIN
;WITH t1(N) AS (SELECT N FROM (VALUES(1),(1)) TableValueExpression(N)), -- 2 Rows
t2(N) AS (SELECT 1 FROM t1 x, t1 y), -- 4 Rows (2*2)
t3(N) AS (SELECT 1 FROM t2 x, t2 y), -- 16 Rows (4*4)
t4(N) AS (SELECT 1 FROM t3 x, t3 y), -- 256 Rows (16*16)
t5(N) AS (SELECT 1 FROM t4 x, t4 y), -- 65,536 Rows (256*256)
tally(N) AS (SELECT 0 UNION ALL
SELECT TOP (DATEDIFF(WEEK, @startDate, @endDate)) -- Limit the result-set straight up front
ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
FROM t5 x, t5 y) -- 4,294,967,296 Rows (65,536*65,536)
SELECT N + 1 AS WeekNo,
CASE WHEN DATEADD(WEEK, DATEDIFF(WEEK, '1900-01-02', DATEADD(WEEK, N, @startDate)), '1900-01-02') < @startDate
THEN @startDate
ELSE DATEADD(WEEK, DATEDIFF(WEEK, '1900-01-02', DATEADD(WEEK,N , @startDate)), '1900-01-02') END AS weekStart,
CASE WHEN DATEADD(WEEK, DATEDIFF(WEEK, '1900-01-08', DATEADD(WEEK, N + 1, @startDate)), '1900-01-08') > @endDate
THEN @endDate
ELSE DATEADD(WEEK, DATEDIFF(WEEK, '1900-01-08', DATEADD(WEEK, N + 1, @startDate)), '1900-01-08') END AS weekEnd
FROM tally;