枢轴的替代方案

时间:2017-01-30 12:24:22

标签: sql-server pivot

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

(我正在使用sql server 2008)

我有这张桌子(替补):

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   

我尝试使用pivot:

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

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

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

谢谢。

1 个答案:

答案 0 :(得分:5)

您不需要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;

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

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;