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

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...