I have the following table in my MS SQL server:
User | Item | Date
1 | A | 2015-03-01
1 | B | 2015-03-03
1 | C | 2015-03-02
1 | A | 2015-03-05
2 | C | 2015-03-01
2 | C | 2015-03-03
2 | B | 2015-03-02
And this table should be aggregated / pivoted / transposed into this:
User | 1st_item | 2nd_item | 3rd_item | 4th_item
1 | A | C | B | A
2 | C | B | C | NULL
(The order of the items is defined by the date in the original data.) Unfortunately I have no clue how to get there... Ideally the solution would also work for a flexible number of items (not fixed to 4 as in the example).
What I tried so far:
- I used ROW_NUMBER() OVER (PARTITION BY user ORDER BY date) to generate a column giving me the order within each user's items
- I tried using PIVOT - but here I have no clue how to get the items into the columns added by this command
Thanks for any help and/or hint in advance!