I have a table in SQL Server of the form:
| date | userId | sessionStartTime | SessionEndTime | nClicks |
|---|---|---|---|---|
| 2020-01-01 | 0 | 9:00:00 | 9:15:10 | 4 |
| 2020-01-01 | 0 | 9:33:00 | 10:05:05 | 2 |
| 2020-01-01 | 2 | 9:05:20 | 9:25:55 | 9 |
| ... | ... | ... | ... | ... |
I'm looking to PIVOT it by userId and date and get something that consolidates the other columns as a JSON array. The output is envisioned to look like:
| date | userId | data |
|---|---|---|
| 2020-01-01 | 0 | [{'sessionStartTime':9:00:00, 'SessionEndTime':9:15:10, 'nClicks':4}, {'sessionStartTime':9:33:00, 'SessionEndTime':10:05:05, 'nClicks':2}] |
| 2020-01-01 | 2 | [{'sessionStartTime':9:05:20, 'SessionEndTime':9:25:55, 'nClicks':9}] |
| ... | ... | ... |
Any ideas on how you could achieve this in SQL (T-SQL)?