单个表的SQL Pivot视图

时间:2018-06-29 21:27:40

标签: sql sql-server view

有一张桌子:

Nomber    Sce    SceValue
10        A      a1b2c3
20        C      d2v3b4
10        B      42b2c3
10        B      5978c3
20        A      edr432

我需要使用一个视图创建以下列表,其中为每个单独的“ Nomber”(最大9对)显示了所有可能的“ Sce”和“ SceValue”对:

Nomber    Sce1    SceValue1    Sce2    SceValue2  ...    Sce9    SceValue9
10        A       a1b2c3       B       42b2c3            B       5978c3
20        C       d2v3b4       A       edr432

我想使用View来实现。这可能吗?

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

select number,
       max(case when seqnum = 1 then Sce end) as sce_1,
       max(case when seqnum = 1 then SceValue end) as SceValue_1,
       max(case when seqnum = 2 then Sce end) as sce_2,
       max(case when seqnum = 2 then SceValue end) as SceValue_2,
       . . .
       max(case when seqnum = 9 then Sce end) as sce_9,
       max(case when seqnum = 9 then SceValue end) as SceValue_9
from (select t.*,
             row_number() over (partition by nomber order by sce) as seqnum
      from t
     ) t
group by nomber;