如果我有下表:
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个帐户完成此操作,这样我就可以尝试为x个具有y个汇总数的帐户创建动态并将它们放入一个变量列结果中,但我似乎无法看到通过使用PIVOT或SELECT CASE使其工作。任何帮助或链接将不胜感激。
答案 0 :(得分: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