SQL将行分组为列

时间:2018-07-19 02:30:01

标签: sql sql-server

我需要帮助将分组的行更改为列。

ColGroup      Code            
===================
1        A001
1        A001
1        A001   
2        A002
2        A002
3        A003

进入

1         2       3
===================
A001    A002    A003
A001    A002 
A001 

谢谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合来做到这一点:

select max(case when colgroup = 1 then code end) as [1],
       max(case when colgroup = 2 then code end) as [2],
       max(case when colgroup = 3 then code end) as [3]
from (select t.*,
             row_number() over (partition by colgroup order by (select null)) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;

答案 1 :(得分:2)

我已经尝试过了。我没有得到确切的结果,但这可能对您有帮助http://www.sqlfiddle.com/#!9/4ecf6c/4