I've got this table ratings:
| id | user_id | type | value |
|---|---|---|---|
| 0 | 0 | Rest | 4 |
| 1 | 0 | Bar | 3 |
| 2 | 0 | Cine | 2 |
| 3 | 0 | Cafe | 1 |
| 4 | 1 | Rest | 4 |
| 5 | 1 | Bar | 3 |
| 6 | 1 | Cine | 2 |
| 7 | 1 | Cafe | 5 |
| 8 | 2 | Rest | 4 |
| 9 | 2 | Bar | 3 |
| 10 | 3 | Cine | 2 |
| 11 | 3 | Cafe | 5 |
I want to have a table with a row for every pair (user_id, type) for the top 3 rated types through all users (ranked by sum(value) across the whole table).
Desired result:
| user_id | type | value |
|---|---|---|
| 0 | Rest | 4 |
| 0 | Cafe | 1 |
| 0 | Bar | 3 |
| 1 | Rest | 4 |
| 1 | Cafe | 5 |
| 1 | Bar | 3 |
| 2 | Rest | 4 |
| 3 | Cafe | 5 |
| 2 | Bar | 3 |
I was able to do this with two queries, one to get the top 3 and then another to get the rows where the type matches the top 3 types.
Does someone know how to fit this into a single query?