将数据从COLUMNS更改为ROW MSSQL

时间:2018-10-10 11:01:01

标签: sql-server sql-server-2008

我列出了一些数据,如附件图片

SELECT Code, compCode FROM KitItems

数据当前的格式如下:

enter image description here

但我希望将其转置为许多列

赞:

enter image description here

任何想法

1 个答案:

答案 0 :(得分:1)

您可以使用row_number()并进行条件聚合:

select code, 
       max(case when seq = 1 then compcode end) as one,
       max(case when seq = 2 then compcode end) as two,
       . . .
       max(case when seq = 7 then compcode end) as seven
from (select t.*,
             row_number() over (partition by code order by compcode) as seq
      from table t
     ) t
group by code;

如果PIVOT有太多的code,则可以通过动态compcode SQL实现相同的目的。