Skip to content
Advertisement

Transpose rows to columns using multiple pivots

I am trying to transpose rows to columns without any luck . What I have now

WEEK_NUMBER VAL9 VAL4 VAL5 VAL7
45 63.27% 28.58% 7.92% 0.23%
52 65.66% 26.16% 7.80% 0.38%
50 90.97% 8.45% 0.29% 0.29%
46 82.49% 12.43% 3.01% 2.06%
47 66.33% 29.53% 3.77% 0.36%
51 65.36% 31.83% 2.69% 0.11%
49 61.88% 28.29% 9.46% 0.37%
44 45.34% 45.55% 8.45% 0.66%
48 43.75% 40.01% 16.01% 0.23%

this is based on the following query

I am trying to get following result

01 02 .. 51 52
VAL9 0 0 .. 65.36% 65.66%
VAL4 0 0 .. 31.83% 26.16%
VAL5 0 0 .. 2.69% 7.80%
VAL7 0 0 .. 0.11% 0.38%

I have tried by doing next query but with no luck . If someone can just point me in the right direction I would appreciate.

Advertisement

Answer

UNPIVOT and then PIVOT:

Which, for the sample data:

Outputs:

KEY 01 02 44 45 46 47 48 49 50 51 52 53
VAL9 null null null 45.34 63.27 82.49 66.33 43.75 61.88 90.97 65.36 65.66
VAL4 null null null 45.55 28.58 12.43 29.53 40.01 28.29 8.45 31.83 26.16
VAL5 null null null 8.45 7.92 3.01 3.77 16.01 9.46 .29 2.69 7.8
VAL7 null null null .66 .23 2.06 .36 .23 .37 .29 .11 .38

db<>fiddle here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement