小二哥's blog

----zhangzs8896(小二)

导航

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

Posted on 2005-06-02 09:39  小二哥  阅读(473)  评论(1)    收藏  举报
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