3

如果我有下表:

Member_Key  Member_Name             col1    Mem1    col2    Mem2    col3    Mem3    col4    Mem4
-----------------------------------------------------------------------------------------------
31          100.00 - Some Account   9       Rollup1 268     Rollup2 246     Rollup3 238   Rollup4
31          100.00 - Some Account   270     Rollup5 271     Rollup6 NULL    NULL    NULL    NULL
31          100.00 - Some Account   283     Rollup7 NULL    NULL    NULL    NULL    NULL    NULL

所需的输出是:

Member_Key    Member_Name    col1  mem1  col2  mem2  col3  mem3 col4 mem4 col5 mem5  col6  mem6  col7  mem7

我一直在尝试使用 1 个帐户完成此操作,以便我可以尝试使其动态化为具有 y 个汇总的 x 个帐户并将它们放入一个可变列结果中,但我似乎无法得到这个通过使用 PIVOT 或 SELECT CASE 工作。任何帮助或链接将不胜感激。

4

1 回答 1

0

我希望以下查询是您的答案:

SELECT *
From
    (SELECT  A.Member_Key,
            A.Member_Name,
            CASE B.n
                WHEN 1 THEN A.Mem1
                WHEN 2 THEN A.Mem2
                WHEN 3 THEN A.Mem3
                WHEN 4 THEN A.Mem4
            END AS Mem,
            CASE B.n
                WHEN 1 THEN A.Col1
                WHEN 2 THEN A.Col2
                WHEN 3 THEN A.Col3
                WHEN 4 THEN A.Col4
            END AS Col
        FROM MyTable A
        CROSS JOIN (SELECT 1 
            UNION SELECT 2
            UNION SELECT 3
            UNION SELECT 4)B(n)
    )AS p
PIVOT (MIN(Col) FOR Mem IN ([Rollup1], [Rollup2], [Rullup3], [Rollup4], [Rollup5], [Rullup6], [Rullup7])) AS Pvt
于 2012-06-07T08:03:25.770 回答