表的纵横转化 sqlserver

在sqlserver中,我有view结果如下:
cardno type day
001 A1 5
001 A2 4
002 A1 3
002 A3 6
……
其中type总共有A1,A2,A3 ……A7七个值,我现在要变成如下表table1:
cardno A1 A2 A3 A4 A5 A6 A7
001 5 4 0 0 0 0 0
002 3 0 6 0 0 0 0


通过递归的select变量可以完成表的横向显示。举个简单的例子:
declare @column varchar(1024)
set @column=''
select @column=@column+cardno+''


select cardno, sum(A1) 'A1',sum(A2) 'A2', sum(A3) 'A3',sum(A4) 'A4', sum(A5) 'A5',sum(A6) 'A6', sum(A7) 'A7'
from
(select cardno,A1 'A1',0 'A2',0 'A3',0 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A1'
union all
select cardno,0 'A1',A2 'A2',0 'A3',0 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A2'
union all
select cardno,0 'A1',0 'A2',A3 'A3',0 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A3'
union all
select cardno,0 'A1',0 'A2',0 'A3',A4 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A4'
union all
select cardno,0 'A1',0 'A2',0 'A3',0 'A4',A5 'A5',0 'A6',0 'A7' from VIEW where TYPE='A5'
union all
select cardno,0 'A1',0 'A2',0 'A3',0 'A4',0 'A5',A6 'A6',0 'A7' from VIEW where TYPE='A6'
union all
select cardno,0 'A1',0 'A2',0 'A3',0 'A4',0 'A5',0 'A6',A7 'A7' from VIEW where TYPE='A7'
)a
group by cardno

select cardno, sum(A1) 'A1',sum(A2) 'A2', sum(A3) 'A3',sum(A4) 'A4', sum(A5) 'A5',sum(A6) 'A6', sum(A7) 'A7'
from (
select cardno,day 'A1',0 'A2',0 'A3',0 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A1'
union all
select cardno,0 'A1',day 'A2 ',0 'A3',0 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A2'
union all
select cardno,0 'A1',0 'A2 ',day 'A3',0 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A3'
union all
select cardno,0 'A1',0 'A2',0 'A3',day 'A4',0 'A5',0 'A6',0 'A7' from VIEW where TYPE='A4'
union all
select cardno,0 'A1',0 'A2',0 'A3',0 'A4',day 'A5',0 'A6',0 'A7' from VIEW where TYPE='A5'
union all
select cardno,0 'A1',0 'A2',0 'A3',0 'A4',0 'A5',day 'A6',0 'A7' from VIEW where TYPE='A6'
union all
select cardno,0 'A1',0 'A2',0 'A3',0 'A4',0 'A5',0 'A6',day 'A7' from VIEW where TYPE='A7'
)a group by cardno


declare @sql varchar(8000)
  
  set @sql = 'select cardno,'
  
  select @sql = @sql + '(case type when '''+type +'''
  
  then day else 0 end) as '''+type +''','
  
  from (select distinct type from view) as a
  
  select @sql = left(@sql,len(@sql)-1) + ' from view group by cardno'
  
  exec(@sql)
  
  go
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值