微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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,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 '李四',100 union all
select '李四',50  union all
select '李四',50  union all
select '王五',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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐