你必须使用动态 SQLPIVOT
来实现你的目标
DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX)
SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME('week ' + CONVERT(NVARCHAR(2), DATEPART(isowk, adate))
+ ' - ' + CONVERT(NVARCHAR(4), YEAR(adate)))
FROM Table1
ORDER BY 1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @sql = 'SELECT type, ' + @cols +
' FROM
(
SELECT type,
''week '' + CONVERT(NVARCHAR(2), DATEPART(isowk, adate))
+ '' - ''
+ CONVERT(NVARCHAR(4), YEAR(adate)) week,
COUNT(*) type_count
FROM table1
WHERE adate BETWEEN ''20130101'' AND ''20131231''
GROUP BY type, YEAR(adate), DATEPART(isowk, adate)
) x
PIVOT
(
MAX(type_count) FOR week IN (' + @cols + ')
) p
ORDER BY type'
EXECUTE(@sql)
样本输出:
| 类型 | 第 1 周 - 2013 年 | 第 2 周 - 2013 年 |
--------------------------------------
| 一个 | 4 | 1 |
| 乙| 2 | 2 |
这是SQLFiddle演示