Hi I want to know how can do a pivot table with crosstable in a table like:
| user_id | action | time |
|---|---|---|
| 1 | a | 2022-01-01 12:30 |
| 1 | b | 2022-01-01 12:40 |
| 1 | b | 2022-01-01 12:50 |
| 1 | c | 2022-01-01 13:00 |
| 1 | c | 2022-01-01 13:10 |
| 1 | c | 2022-01-01 13:20 |
| 2 | b | 2022-01-01 13:11 |
| 2 | c | 2022-01-01 13:21 |
The expected result should look like this:
| user_id | a | b | c |
|---|---|---|---|
| 1 | 2022-01-01 12:30 | 2022-01-01 12:40 | 2022-01-01 13:00 |
| 1 | NULL | 2022-01-01 12:50 | 2022-01-01 13:10 |
| 1 | NULL | NULL | 2022-01-01 13:20 |
| 2 | NULL | 2022-01-01 13:11 | 2022-01-01 13:21 |
Following several tutorials, they gave me this result:
| user_id | a | b | c |
|---|---|---|---|
| 1 | 2022-01-01 12:30 | 2022-01-01 12:40 | 2022-01-01 13:00 |
| 2 | NULL | 2022-01-01 13:11 | 2022-01-01 13:21 |
However, as you can note, there is plenty of data loss by the single line result. Does any have an idea, please? Thanks in advance
Here is the SQL:
Output:
Setup:
Ideal SQL should include user_id for action A, B, C so that those not missed out . Here the situation does not arise because USER_ID is only 1 and all actions are mapped to USER_ID. I believe might get different, in which case you might need this SQL: