的我有3個表:SQL(postgres的)加入在可變數目子選擇
- 店鋪{ 'ID', 'NAME'}
- 產物{ 'ID', 'NAME'}
- 訂單{ 'SHOP_ID', 'PRODUCT_ID', '數量'}
的orders
表被引用到product.id
用於銷售的產品在商店與shop.id
。
我想創建一個sql視圖,選擇每個商店的前10名產品。因此,我希望結果表格有10行(每個等級一個)以及shop
表中存在商店ID的列數,每列中有10個商店的賣家。
獲得每個商店的十大產品很容易。它也很容易得到這個固定數量的n個商店通過重複和加入選擇從一個商店得到這個,但我不知道如何做到這一點爲可變數量的商店。 我搜索了類似的例子,我的感覺是,這應該是可能的公用表表達式,但我不明白。
所以,問題是:
如何加入一個循環或類似的結構
例的結果應該如何看起來像一個可變數量的子選擇的:
'RANK' 'Berlin' 'Hamburg' 'München'
1 2 3 4
2 . . .
. . . .
. . . .
9 . . .
10 . . x
在哪裏這些數字是前10名賣家的產品ID。 也就是說這些列被創建爲xx.product_id,如'Berlin'。
這給了我的商店十個產品,但在行而不是列。 – Peter 2015-03-31 14:19:16