<script language='javascript' src='http://www.shiqiaotou.com/donetk/Header.js'></script>1 .最基本的行列转换:
文章来源于 http://www.cnblogs.com/zhangzs8896 版权归原作者所有<script language='javascript' src='http://www.shiqiaotou.com/donetk/Footer.js'></script>
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
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>