Question

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  | amtC2

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top