我有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
在上表中,我需要分析供应商为每个询价提交最低和最高出价的次数。
预期产量:
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
通过窗口函数将供应商的数量与最小值和最大值进行比较,并在外部查询级别上运行条件计数:
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。