不等记录数的行列转换
如何实现将表中的行变为列:
表 tab
大类号 小类号
A a1
A a2
A a2
B b1
C c1
C c2
通过SQL语句实现如下转换:
A B C
a1 b1 c1
a2 c2
a2
------解决方案--------------------create table #aa (mx varchar(20),mi varchar(20))
insert into #aa
select 'A ', 'a1 ' union all
select 'A ', 'a2 ' union all
select 'A ', 'a3 ' union all
select 'B ', 'b1 ' union all
select 'C ', 'c1 ' union all
select 'C ', 'c2 '
select
max(case when mx= 'a ' then mi end) A,
max(case when mx= 'b ' then mi end) b,
max(case when mx= 'c ' then mi end) c
from
(select *,(select count(1) from #aa where a.mx=mx and a.mi> =mi) co from #aa a)a
group by co
A b c
-------------------- -------------------- --------------------
a1 b1 c1
a2 NULL c2
a3 NULL NULL
(所影响的行数为 3 行)