日期:2014-05-17 浏览次数:20511 次
USE test
GO
---->生成表tb
--if object_id('tb') is not null
-- drop table tb
--Go
---- test data
--Create table tb([日期] datetime,[OrderNr] nvarchar(3),[CustomerName] nvarchar(1))
--Insert into tb
--Select '2012-01-01',N'#1',N'A'
--Union all Select '2012-01-02',N'#2',N'A'
--Union all Select '2012-01-03',N'#3',N'A'
--Union all Select '2012-01-04',N'#4',N'A'
--Union all Select '2012-02-01',N'#5',N'A'
--Union all Select '2012-02-02',N'#6',N'B'
--Union all Select '2012-02-03',N'#7',N'B'
--Union all Select '2012-05-14',N'#8',N'B'
--Union all Select '2012-05-16',N'#9',N'C'
--Union all Select '2012-05-18',N'#10',N'B'
--Union all Select '2012-05-19',N'#11',N'C'
--Union all Select '2012-09-05',N'#12',N'A'
--Union all Select '2012-09-06',N'#13',N'D'
--Union all Select '2012-09-07',N'#14',N'D'
--Union all Select '2013-01-06',N'#14',N'D'
--Union all Select '2013-01-07',N'#14',N'D'
;WITH Result AS (
SELECT YEAR(日期) AS [Year],DATEPART(Week,日期) AS [Week],* FROM tb
)
SELECT
COUNT(a.日期) AS [Count]
,b.[Week]
,b.[Year]
FROM Result AS a
RIGHT JOIN (
SELECT
t.Year,t2.Week
FROM (
SELECT DISTINCT
Year
FROM Result
) t,(
SELECT TOP 52
ROW_NUMBER()OVER(ORDER BY getdate()) AS [Week]
FROM sys.syscolumns
) t2
WHERE t2.Week>=(SELECT MIN(Week) FROM Result AS x WHERE x.Year=t.Year)
AND t2.Week<=(SELECT MAX(Week) FROM Result AS x WHERE x.Year=t.Year)
) AS b ON a.Year=b.Year AND a.Week=b.Week
GROUP BY b.[Week],b.[Year]
ORDER BY b.[Year],b.[Week]
/*
Count Week Year
------ ----- -----
4 1 2012
0 2 2012
0 3 2012
0 4 2012
3 5 2012
0 &