I need to do an advanced selection in SQL, but I'm stuck.
I have the following table:
id | user_id | position | value
1 | 1 | 1 | 1
1 | 1 | 2 | 1
1 | 1 | 3 | 3
1 | 2 | 1 | 2
1 | 2 | 2 | 2
1 | 2 | 3 | 2
1 | 3 | 1 | 3
1 | 3 | 2 | 2
1 | 3 | 3 | 1
I need a query that gives me a result set ordered as this:
- Total sum for each user (user 1: 5, user 2: 6, user 3: 6)
- Value for position 3 for each user (user 1: 3, user 2: 2, user 3: 1)
- Val for pos 3 + val for pos 2 for each user (user 1: 4, user 2: 4, user 3: 4)
- Val for pos 3 + val for pos 2 + val for pos 1 for each user (user 1: 5, user 2: 6, user 3: 6)
This is just an example, the table can actually contain more positions, so I need a query that is not hard coded on three positions.
NOTE: There is always the same number of positions for each user_id. In this example it's three, but I could as well truncate the table and add data for each user using five positions.
An ugly solution is to assume that there are never no more than ten positions, creating pos1, pos2, and so on as columns and just add them accordingly in the query. If you only use three positions you get a lot of NULL values and you also get stuck with a maximum of ten positions.
I have considered the use of temporary tables, but haven't found a breakthrough there either.
How would you do it?