SQL SERVER 2008的转置函数PIVOT

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
复制代码

则显示结果:

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值