【问题标题】:Alternative to pivot替代枢轴
【发布时间】:2017-01-30 12:24:21
【问题描述】:

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

(我正在使用 sql server 2008)

我有这张桌子(替代):

位号 |替换escr |替代代码 37664 | EANCUTIE3 | 14902778788926 37664 | EAN1 | 4902778788929 37664 | EANCUTIE1 | 4902778931653 37664 | EANCUTIE2 | 4902778931738

我希望选择看起来像这样:

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

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

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

谢谢。

【问题讨论】:

    标签: sql-server pivot


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答:D 解决了我的问题。
    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多