摘要:SQL - 使用 PIVOT
從以前到現在再處理年度或是季的銷售資料總是讓人覺得麻煩,在不知道 PIVOT 時,應該會下很多的 T-SQL 來處理。自從 SQL Server 2005 開始就提供 PIVOT 這個很好用的語法,以下就來實作一下唄...
資料:
銷售業績
銷售業績By季
Code:
Select * From dbo.銷售業績 Order By 年份, 月份
SELECT
年份,
[01] as '一月', [02] as '二月', [03] as '三月', [04] as '四月',
[05] as '五月', [06] as '六月', [07] as '七月', [08] as '八月',
[09] as '九月', [10] as '十月', [11] as '十一月', [12] as '十二月'
FROM (
SELECT 年份, 月份, 銷售量
FROM dbo.銷售業績
GROUP BY 年份, 月份, 銷售量
) as GroupTable
PIVOT
(
Sum(銷售量)
FOR 月份 IN ([01], [02], [03], [04], [05], [06], [07], [08], [09], [10], [11], [12])
) AS PivotTable
結果:
Code:
Select * From dbo.[銷售業績By季] Order By 年份, 季, 月份
SELECT
年份,
[Q1] as '第一季', [Q2] as '第二季', [Q3] as '第三季', [Q4] as '第四季'
FROM (
SELECT 年份, 季, SUM(銷售量) as '季加總'
FROM dbo.[銷售業績By季]
GROUP BY 年份, 季
) as GroupTable
PIVOT
(
Sum(季加總)
FOR 季 IN ([Q1], [Q2], [Q3], [Q4])
) AS PivotTable
結果:
參考:
使用 PIVOT 和 UNPIVOT