您可以使用動態SQL動態創建列,但是,我真的建議在爲其設計的圖層中處理動態軸,例如SSRS或Excel。
DECLARE @SQL NVARCHAR(MAX) = '',
@SQL2 NVARCHAR(MAX) = '',
@SQL3 NVARCHAR(MAX) = '';
-- COMPILE THE UNIQUE VALUES FOR ARRIVAL THAT NEED TO BE PIVOTED
SELECT @SQL = @SQL + ',' + QUOTENAME(Arrival),
@SQL2 = @SQL2 + '+ISNULL(' + QUOTENAME(Arrival) + ', 0)',
@SQL3 = @SQL3 + ',' + QUOTENAME(Arrival) + ' = ISNULL(' + QUOTENAME(Arrival) + ', 0)'
FROM (SELECT DISTINCT Arrival FROM tblSource) s;
-- COMBINE THEM INTO A SINGLE QUERY
SET @SQL = 'SELECT [Prov]' + @SQL3 + ', [Total] = ' + STUFF(@SQL2, 1, 1, '') + '
FROM ( SELECT Arrival, Prov, Amount
FROM [tblSource]
UNION ALL
SELECT Arrival, ''Total'', SUM(Amount)
FROM [tblSource]
GROUP BY Arrival
) up
PIVOT
( SUM(Amount)
FOR Arrival IN (' + STUFF(@SQL, 1, 1, '') + ')
) pvt;';
-- EXECUTE THE QUERY
EXECUTE SP_EXECUTESQL @SQL;
這將創建並執行下面的SQL:
SELECT [Prov],
[2013-01-01] = ISNULL([2013-01-01], 0),
[2013-02-01] = ISNULL([2013-02-01], 0),
[Total] = ISNULL([2013-01-01], 0) + ISNULL([2013-02-01], 0)
FROM ( SELECT Arrival, Prov, Amount
FROM [tblSource]
UNION ALL
SELECT Arrival, 'Total', SUM(Amount)
FROM [tblSource]
GROUP BY Arrival
) up
PIVOT
( SUM(Amount)
FOR Arrival IN ([2013-01-01],[2013-02-01])
) pvt;
它是在底部增加了總排子查詢up
低於工會查詢,該行總僅通過增加創建該行中的所有列。
Example on SQL Fiddle
我會再次強調,雖然,我真的建議處理數據的操作是這樣的外部SQL的。
編輯
使用UNION得到總行是使用GROUPING SETS
如下替代:
DECLARE @SQL NVARCHAR(MAX) = '',
@SQL2 NVARCHAR(MAX) = '',
@SQL3 NVARCHAR(MAX) = '';
-- COMPILE THE UNIQUE VALUES FOR ARRIVAL THAT NEED TO BE PIVOTED
SELECT @SQL = @SQL + ',' + QUOTENAME(Arrival),
@SQL2 = @SQL2 + '+ISNULL(' + QUOTENAME(Arrival) + ', 0)',
@SQL3 = @SQL3 + ',' + QUOTENAME(Arrival) + ' = ISNULL(' + QUOTENAME(Arrival) + ', 0)'
FROM (SELECT DISTINCT Arrival FROM tblSource) s;
-- COMBINE THEM INTO A SINGLE QUERY
SET @SQL = 'SELECT [Prov]' + @SQL3 + ', [Total] = ' + STUFF(@SQL2, 1, 1, '') + '
FROM ( SELECT Arrival, Prov = ISNULL(Prov, 'Total'), Amount = SUM(Amount)
FROM [tblSource]
GROUP BY GROUPING SETS((Prov, arrival), (arrival))
) up
PIVOT
( SUM(Amount)
FOR Arrival IN (' + STUFF(@SQL, 1, 1, '') + ')
) pvt;';
-- EXECUTE THE QUERY
EXECUTE SP_EXECUTESQL @SQL;
我想補充ROLLUP到您的解決方案。 OP要求每行列出總計。 – Taryn
謝謝 - 我把它推到一個網頁上,SSRS對於我們在快速響應和移動友好解決方案中所需要的並不理想,但我確實把它放在了船上。我可能只是建立功能到頁面本身。謝謝。 – pee2pee
@bluefeet不會''ROLLUP'與'PIVOT'一起使用嗎?我通過向查詢添加聯合並重複數據來照顧Total行。我現在使用'GROUPING SETS'添加了一個替代方案。 – GarethD