从产品和供应商那里获得最低价格
Posted
技术标签:
【中文标题】从产品和供应商那里获得最低价格【英文标题】:Get the lowest price from a product and the provider for that price 【发布时间】:2021-05-03 08:09:45 【问题描述】:我正在查询一项学校作业,其中我选择了低于最低库存的产品,然后我选择了以最低价格提供每种产品的供应商。
这些是桌子。
+------------+
+------------------+
+------------+
| products |
| product_overview |
| provider |
+------------+
+------------------+
+------------+
| productID |
| productID |
| providerID |
| name |
| providerID |
| name |
| stock |
| price |
+------------+
| min_stock |
+------------------+
+------------+
这是我目前所拥有的。
SELECT p.name, pr.name
FROM products p JOIN product_overview po ON p.productID = po.productID
JOIN provider l ON po.providerID = pr.providerID
WHERE p.stock < p.min_stock
GROUP BY po.productID
ORDER BY p.name;
我寻找哪些产品有stock < min_stock
,然后寻找供应商。目前,输出中给出的供应商并不是以最低价格交付产品的供应商。
【问题讨论】:
【参考方案1】:最简单的方法是使用窗口函数:
SELECT pp.*
FROM (SELECT p.name as product_name, pr.name as provider_name,
ROW_NUMBER() OVER (PARTITION BY p.productID ORDER BY po.price ASC) as seqnum
FROM products p JOIN
product_overview po
ON p.productID = po.productID JOIN
provider pr
ON po.providerID = pr.providerID
WHERE p.stock < p.min_stock
) pp
WHERE seqnum = 1
ORDER BY p.name;
【讨论】:
【参考方案2】:你可以使用not exists
如下:
SELECT p.name, pr.name provider_name, po.price
FROM products p JOIN product_overview po ON p.productID = po.productID
JOIN provider pr ON po.providerID = pr.providerID
WHERE p.stock < p.min_stock
AND not exists
(select 1 from product_overview poo
where poo.productID = po.productID
and poo.price < po.price)
【讨论】:
以上是关于从产品和供应商那里获得最低价格的主要内容,如果未能解决你的问题,请参考以下文章