PIVOT函数用于转置数据,即用旋转表的方式把行换成列。PIVOT可以将表中的列换成行
如下面的例子:
CREATE TABLE Sales.SalesByMonth ( year char(4), month char(3), amount MONEY, PRIMARY KEY(year,month) ) INSERT INTO Sales.SalesByMonth(year,month,amount) values('2007','Jan',789.0000), ('2007','Feb',389.0000), ('2007','Mar',8867.0000), ('2007','Apr',778.0000), ('2007','May',78.0000), ('2007','Jun',9.0000), ('2007','Jul',987.0000), ('2007','Aug',866.0000), ('2007','Sep',7787.0000), ('2007','Oct',85576.0000), ('2007','Nov',855.0000), ('2007','Dec',5875.0000), ('2008','Jan',7.0000), ('2008','Feb',6868.0000), ('2008','Mar',688.0000), ('2008','Apr',9897.0000) SELECT YEAR, SUM(case when month='Jan' then amount else 0 end) as 'Jan', SUM(case when month='Feb' then amount else 0 end) as 'Feb', SUM(case when month='Mar' then amount else 0 end) as 'Mar', SUM(case when month='Apr' then amount else 0 end) as 'Apr', SUM(case when month='May' then amount else 0 end) as 'May', SUM(case when month='Jun' then amount else 0 end) as 'Jun', SUM(case when month='Jul' then amount else 0 end) as 'Jul', SUM(case when month='Aug' then amount else 0 end) as 'Aug', SUM(case when month='Sep' then amount else 0 end) as 'Sep', SUM(case when month='Oct' then amount else 0 end) as 'Oct', SUM(case when month='Nov' then amount else 0 end) as 'Nov', SUM(case when month='Dec' then amount else 0 end) as 'Dec' FROM Sales.SalesByMonth group by year select YEAR,[Jan],[Feb],[Mar],[Apr],[May],[Jun], [Jul],[Aug],[Sep],[Oct],[Nov],[Dec] FROM (Select YEAR,amount,month from Sales.SalesByMonth) as SalesByMonth pivot (sum(amount) for month in ( [Jan],[Feb],[Mar],[Apr],[May],[Jun], [Jul],[Aug],[Sep],[Oct],[Nov],[Dec] )) as ourPivot order by year
显示结果为:
如果去掉year选项,语句改为:
select [Jan],[Feb],[Mar],[Apr],[May],[Jun], [Jul],[Aug],[Sep],[Oct],[Nov],[Dec] FROM (Select amount,month from Sales.SalesByMonth) as SalesByMonth pivot (sum(amount) for month in ( [Jan],[Feb],[Mar],[Apr],[May],[Jun], [Jul],[Aug],[Sep],[Oct],[Nov],[Dec] )) as ourPivot
则显示结果: