开发者

T-SQL help with multiple pivot / unpivot

I am not sure what will be the best approch pivot or unpivot. I have following column in one table.


group1 | group2 | group3 | amtA1 | amtA2 | amtB1 | amtB2 | amtC1 | amtC1

and I need to product table like


group1
X | amtA1  | amtB1  | amtC1
Y | amtA2  | amtB2  | amtC2

group2
X | amtA1  | amtB1  | amtC1
Y | amtA2  | amtB2  | amtC2

group3
X | amtA1  | amtB1  | amtC1
Y | amtA2  | amtB2  | a开发者_如何学JAVAmtC2

I try my best however couldn't figure out. Any help will be appreciated.


Try

SELECT group1 As Group, "X" as ColType, amtA1 as ColA,  amtB1 as ColB, amtC1 as ColC
UNION
SELECT group1, "Y", amtA2,  amtB2, amtC2
UNION 
SELECT group2, "X", amtA1,  amtB1, amtC1
UNION 
SELECT group2, "Y", amtA2,  amtB2, amtC2
UNION 
SELECT group3, "X", amtA1,  amtB1, amtC1
UNION 
SELECT group3, "Y", amtA2,  amtB2, amtC2

You can now easily group based on the "Group" column.

although I would be having a "discussion" about table normalisation with someone in your organisation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜