Postgres:获取多对多关系中的最小和最大行数 table
Postgres : get min and max rows count in many to many relation table
我有 RFQ(询价)和供应商投标金额的映射 table。
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
在上面table中,我想分析供应商为每个 RFQ 提交了多少次最低和最高出价。
预期输出:
vendor_id min_bid_count max_bid_count
-----------------------------------------
1 1 2
2 2 1
3 1 2
4 1 0
将供应商的金额与 window 函数的最小值和最大值以及 运行 外部查询级别的条件计数进行比较:
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;
我有 RFQ(询价)和供应商投标金额的映射 table。
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
在上面table中,我想分析供应商为每个 RFQ 提交了多少次最低和最高出价。
预期输出:
vendor_id min_bid_count max_bid_count
-----------------------------------------
1 1 2
2 2 1
3 1 2
4 1 0
将供应商的金额与 window 函数的最小值和最大值以及 运行 外部查询级别的条件计数进行比较:
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;