SQL Server 行列转换示例

SQL Server的行列转换功能非常实用,但是由于其语法不好懂,使很多初学者都不愿意使用它。下面我就用示例的形式,逐一展现Pivot和UnPivot的魅力。如下图

聚合图

 由于近期CSDN的图片服务器不稳定,如果图片挂了,请读者访问图片原地址:

http://img242.ph.126.net/4isS79TpI8jxQViyLD410Q==/2136958023189057751.jpg

1.从Wide Table of Months 转换到 Narrow Table的示例

  
  
[c-sharp] view plain copy print ?
  1. select [Year],[Month],[Sales] from  
  2. (  
  3.     select * from MonthsTable  
  4. )p  
  5. unpivot  
  6. (  
  7.     [Sales] for [Year] in ([2001],[2002],[2003])  
  8. )t  
  9. order by [Year]  

2.从Narrow Table 转换到 Wide Table of Years的示例

  
  
[c-sharp] view plain copy print ?
  1. select * from  
  2. (  
  3.     select * from NarrowTable  
  4. )p  
  5. pivot  
  6. (  
  7.     Sum(Sales) for [Month] in ([Jan],[Feb],[Mar])  
  8. )t  
 

3.从Wide Table of Months 转换到 Wide Table of Years的示例

  
  
[c-sharp] view plain copy print ?
  1. with d as  
  2. (  
  3. select [Year],[Month],[Sales] from  
  4. (  
  5.     select * from MonthsTable  
  6. )p  
  7. unpivot  
  8. (  
  9.     [Sales] for [Year] in ([2001],[2002],[2003])  
  10. )t  
  11. )  
  12. select * from   
  13. (  
  14.     select * from d  
  15. )p  
  16. pivot  
  17. (  
  18.     Sum(Sales) for [Month] in ([Jan],[Feb],[Mar])  
  19. )t  
 

4.从Wide Table of Years 转换到 Narrow Table的示例

[c-sharp] view plain copy print ?
  1. select [Year],[Month],[Sales] from  
  2. (  
  3.     select * from YearTable  
  4. )p  
  5. unpivot  
  6. (  
  7.     Sales for [Month] in ([Jan],[Feb],[Mar])  
  8. )t  
  

5.从Narrow Table 转换到 Wide Table of Month的示例

  
  
[c-sharp] view plain copy print ?
  1. select * from  
  2. (  
  3.     select * from NarrowTable  
  4. )p  
  5. pivot  
  6. (  
  7.     Sum(Sales) for [Year] in ([2001],[2002],[2003])  
  8. )t  
 

6.从Wide Table of Years 转换到 Wide Table of Month的示例

[c-sharp] view plain copy print ?
  1. with d as  
  2. (  
  3. select [Year],[Month],[Sales] from  
  4. (  
  5.     select * from YearTable  
  6. )p  
  7. unpivot  
  8. (  
  9.     Sales for [Month] in ([Jan],[Feb],[Mar])  
  10. )t  
  11. )  
  12. select * from  
  13. (  
  14.     select * from d  
  15. )p  
  16. pivot  
  17. (  
  18.     Sum(Sales) for [Year] in ([2001],[2002],[2003])  
  19. )t  

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值