加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver 行转列 列转行

发布时间:2020-12-12 14:30:32 所属栏目:MsSql教程 来源:网络整理
导读:---行转列 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

---行转列
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读