這是PIVOT運算符是什麼:
SELECT
Resource, ClientName,
[JAN2011], [FEB2011], [MAR2011]
FROM
(
SELECT
*
FROM tblname
) AS SourceTable
PIVOT
(
SUM(COST)
FOR MONTHANDYEAR IN ([JAN2011], [FEB2011], [MAR2011])
) AS PivotTable;
由於您的使用@startDate作爲基準月動態選擇月份,則可以使用以下動態查詢:
DECLARE @startDate datetime
SET @startDate = '2011-01-01'
DECLARE @sql varchar(MAX)
SET @sql = 'SELECT
Resource, ClientName, [' +
REPLACE(SUBSTRING(CONVERT(varchar, @startDate, 13), 4, 8), ' ', '') + '], [' +
REPLACE(SUBSTRING(CONVERT(varchar, DATEADD(MONTH, 1, @startDate), 13), 4, 8), ' ', '') + '], [' +
REPLACE(SUBSTRING(CONVERT(varchar, DATEADD(MONTH, 2, @startDate), 13), 4, 8), ' ', '') + ']
FROM
(
SELECT
*
FROM tblName
) AS SourceTable
PIVOT
(
SUM(COST)
FOR MONTHANDYEAR IN (' +
QUOTENAME(REPLACE(SUBSTRING(CONVERT(varchar, @startDate, 13), 4, 8), ' ', '')) + ', ' +
QUOTENAME(REPLACE(SUBSTRING(CONVERT(varchar, DATEADD(MONTH, 1, @startDate), 13), 4, 8), ' ', '')) + ', ' +
QUOTENAME(REPLACE(SUBSTRING(CONVERT(varchar, DATEADD(MONTH, 2, @startDate), 13), 4, 8), ' ', '')) + ')
) AS PivotTable'
execute(@sql)
工作sqlfiddle here
這裏面有多少已經* *在該數據庫上完成結束?例如,您可以在客戶端應用程序中構建您的查詢嗎?或者您是否使用可以進行數據透視/分組的報告解決方案? – 2013-02-22 04:20:26
我們的報告軟件具有非常有限的功能,不能像上述那樣轉置數據。 – 0onetwo 2013-02-22 04:22:21