Closed. This question needs details or clarity。它目前不接受答案。
想改进这个问题吗?添加细节并通过editing this post澄清问题。
三年前关闭。
我有询价(询价)和供应商投标金额的对应表。
询价供应商映射:
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

在上面的表格中,我想分析供应商有多少次为每个询价提交最小和最大出价。
预期产量:
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

最佳答案

通过窗口函数将供应商的金额与min和max进行比较,并在外部查询级别上运行条件计数:

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.

关于sql - Postgres:获取多对多关系表中的最小和最大行数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40435387/

10-11 17:34