sqlserver 行转列 列转行

---行转列
declare @abc table(col1 varchar(20),col2 varchar(20))
insert @abc
select 'A','ddd' union all
select 'B','asdf' union all
select 'C','dsdf' union all
select 'D','eee' union all
select 'E','geas' union all
select 'F','2' union all
select 'G','5d' union all
select 'H','sad' union all
select 'I','ww' union all
select 'J','23' union all
select 'K','asdfw'

select  ib.A,ib.B,ib.C,ib.D,ib.E,
ib.F,ib.G,ib.H,ib.I,ib.J,ib.K
from @abc ia pivot
(
    max(col2)  for col1 in(A,B,C,D,E,F,G,H,I,J,K)
) ib


----列转行
declare @unpivot table(col1 varchar(20),col2 varchar(20))
declare @RowTransfercolumn table(A varchar(20),B varchar(20),C varchar(20),
D varchar(20),E varchar(20),F varchar(20),G varchar(20),H varchar(20),
I varchar(20),J varchar(20),K varchar(20))
insert @RowTransfercolumn(A,B,C,D,E,F,G,H,I,J,K)
select 'ddd','asdf','dsdf','eee','geas','2','5d','sad','ww','23','asdfw'
select col1,col2 from @RowTransfercolumn ia
unpivot(
    col2 for col1 in(A,B,C,D,E,F,G,H,I,J,K)
 
) ie

 

行转列、列传行的综合案例:

/*
  报3门科
    总人数:2人
    通过3门:1人(50%)
    通过2门:0人(50%)
    通过1门:1人(50%)
    通过0门:0人(50%)           
*/

declare @table table(name varchar(255),num varchar(10),score int)
insert into @table(name,num,score)
select '张三' ,'01',100 union all
select '张三' ,'02',90  union all
select '张三' ,'03',60  union all
select '李四' ,'01',100 union all
select '李四' ,'02',50  union all
select '李四' ,'03',50  union all
select '王五' ,'03',100

select I4.col1 as [标题],I4.col2 as [PassPerson] from (
select
 (I2.[0]+I2.[1]+I2.[2]+I2.[3]) as [总人数],
 i2.[3] as [通过3门],
 i2.[2] as [通过2门],
 i2.[1] as [通过1门],
 i2.[0] as [通过0门]
from (
select
    name,
    count(case when score>=60  then num end) as [Pass]
from @table where name in ( select name from @table  group by name  having(count(num) =3)
)group by name
) I1  pivot 
(
  count(name) for Pass in ([0],[1],[2],[3])
)I2
) I3  unpivot
(
   col2 for col1 in ([总人数],[通过3门],[通过2门],[通过1门],[通过0门])
) I4

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值