替代枢轴

Alternative to pivot

我是 sql 语言的新手,需要一些帮助来重新排列数据。

(我正在使用 sql 服务器 2008)

我有这个table(替代):

iteid | substitutedescr  |  substitutecode
37664 | EANCUTIE3        |  14902778788926
37664 | EAN1             |  4902778788929
37664 | EANCUTIE1        |  4902778931653
37664 | EANCUTIE2        |  4902778931738

我希望 select 看起来像这样:

iteid   EAN1            EANCUTIE1           EANCUTIE2       EANCUTIE3
37664                                                       14902778788926
37664   4902778788929           
37664                   4902778931653       
37664                                       4902778931738   

我尝试使用数据透视表:

select *
from (
           select iteid as [ID], substitutedescr as [descr], substitutecode     as [Values]
           from substitute) as s
PIVOT
(
SUM(SUBSTITUTECODE)
FOR [DESCR] in ( ean1, ean2, ean3, eancutie1, eancutie2, eancutie3) 
) as pvt

但似乎我需要将兼容级别设置为更高的值才能激活数据透视功能。

我有其他选择来获得这个结果吗?

谢谢。

你不需要 pivot,只需要 case:

select iteid,
       (case when substitutedescr = 'EAN1' then substitutecode end) as EAN1,
       (case when substitutedescr = 'EANCUTIE1' then substitutecode end) as EANCUTIE1,
       (case when substitutedescr = 'EANCUTIE2' then substitutecode end) as EANCUTIE2,
       (case when substitutedescr = 'EANCUTIE3' then substitutecode end) as EANCUTIE3
from substitute;

如果您希望每个 iteid 一行包含该行上的所有值,您将需要 pivot(或聚合)。例如:

select iteid,
       max(case when substitutedescr = 'EAN1' then substitutecode end) as EAN1,
       max(case when substitutedescr = 'EANCUTIE1' then substitutecode end) as EANCUTIE1,
       max(case when substitutedescr = 'EANCUTIE2' then substitutecode end) as EANCUTIE2,
       max(case when substitutedescr = 'EANCUTIE3' then substitutecode end) as EANCUTIE3
from substitute
group by iteid;