2016-11-05 48 views
2

我有RFQ(報價請求)和供應商出價金額的映射表。Postgres:在多對多關係表中獲取最小和最大行數

rfq_vendor_mapping:

id rfq_id(FK) vendor_id(FK) amount 
--------------------------------------- 

1  1   1   100 
2  1   2   50 
3  2   1   200 
4  2   3   300 
5  2   2   40 
6  3   4   70 
7  3   1   90 
8  3   2   250 
9  4   3   30 
10  5   1   500 

在上面的表格,我要如何廠商多次提交最低和最高出價爲每RFQ分析。

預期輸出:

vendor_id min_bid_count max_bid_count 
----------------------------------------- 
    1   1    2 
    2   2    1 
    3   1    2 
    4   1    0 

http://sqlfiddle.com/#!15/60198/1

+0

很明顯,任何SQL都是「在JPA中受支持的」,如果您期望JPQL,那麼您將不得不爲任何人提供評論的CLASSES。這不是查詢寫入服務。 –

回答

5

從一個窗口函數比較供應商的與最小和最大金額和外部查詢級別運行條件計數:

SELECT vendor_id 
    , count(min_bid OR NULL) AS min_bid_count 
    , count(max_bid OR NULL) AS max_bid_count 
FROM (
    SELECT vendor_id 
     , amount = min(amount) OVER w AS min_bid 
     , amount = max(amount) OVER w AS max_bid 
    FROM rfq_vendor_mapping 
    WINDOW w AS (PARTITION BY rfq_id) 
    ) sub 
GROUP BY 1 
ORDER BY 1; 

SQL Fiddle.

+0

請查看http://stackoverflow.com/questions/40520986/postgres-get-first-and-last-version-for-individual –

相關問題