I have 3 tables:
- shop {'ID','NAME'}
- product {'ID','NAME'}
- orders {'SHOP_ID','PRODUCT_ID','QTY'}
The orders
table is referencing to product.id
for sold products at shop with shop.id
.
I would like to create a an sql view that selects top 10 products per shop. Thus I wish result table to have 10 rows (one per rank) and as many columns as there exist shop ids in the shop
table, with the to 10 sellers for the shop in each column.
Getting the top ten products for each shop is easy. Its also easy to get this for a fixed number of n shops by repeating and joining the selects to get this from a single shop, but I don't know how to do this for a variable number of shops. I searched for similar examples and my feeling is, that this should be possible with a common table expression but I don't get it.
So the question is:
How to join a variable number of sub selects in a loop or similar construct
Example how the result should look like:
'RANK' 'Berlin' 'Hamburg' 'München'
1 2 3 4
2 . . .
. . . .
. . . .
9 . . .
10 . . x
Where the numbers are product IDs of the top 10 sellers. I.e. the columns are created like xx.product_id as 'Berlin'.