Postgres:在多对多关系表中获取最小和最大行数

Dar*_*tel 2 sql postgresql hibernate ejb jpa

我有RFQ(报价请求)和供应商的出价金额的映射表.

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
Run Code Online (Sandbox Code Playgroud)

在上表中,我想分析供应商为每个RFQ提交最低和最高出价的次数.

预期产出:

vendor_id   min_bid_count   max_bid_count
-----------------------------------------
    1           1               2
    2           2               1
    3           1               2
    4           1               0
Run Code Online (Sandbox Code Playgroud)

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

Erw*_*ter 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;
Run Code Online (Sandbox Code Playgroud)

SQL小提琴.