I have a table which has several columns. Except customer column, I want to count them all by themselves. I need to see how many transactions done on "value1" by "customer:100" in segment "1". Which is in this scenario at the bottom, answer is 2.
| customer | value1 | value2 | value3 | value4 | value5 | value6 | value7 | value8 |
|---|---|---|---|---|---|---|---|---|
| 100 | 1 | 2 | 5 | 3 | 2 | 1 | 2 | 1 |
| 100 | 1 | 3 | 4 | 3 | 2 | 5 | 2 | 1 |
| 101 | 3 | 2 | 2 | 2 | 2 | 1 | 2 | 1 |
| 101 | 3 | 2 | 1 | 2 | 1 | 3 | 5 | 2 |
| 101 | 2 | 2 | 5 | 4 | 2 | 3 | 4 | 3 |
I need something like this:
| customer | columns | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 100 | value1 | 2 | 0 | 0 | 0 | 0 |
| 100 | value2 | 0 | 1 | 1 | 0 | 0 |
| 100 | value3 | 0 | 0 | 0 | 1 | 1 |
| 100 | value4 | 0 | 0 | 2 | 0 | 0 |
| 100 | value5 | 0 | 2 | 0 | 0 | 0 |
| 101 | value1 | 0 | 1 | 2 | 0 | 0 |
| 101 | value2 | 0 | 3 | 0 | 0 | 0 |
| 101 | value3 | 1 | 1 | 0 | 0 | 1 |
| 101 | value4 | 0 | 2 | 0 | 1 | 0 |
| 101 | value5 | 1 | 2 | 0 | 0 | 0 |
But I wonder what is the correct way of doing this?
Thanks in advance.
UNPIVOTthe columns and thenPIVOTon the values:Which, for the sample data:
Outputs:
fiddle