每个供应商提供最便宜产品的SQL查询

时间:2017-11-19 17:38:30

标签: sql-server

我需要找到每个供应商最便宜的产品。 我拥有的表是tb_supplier,tb_consumer,tb_offers,tb_requests,tb_transactions和tb_products。

我有以下代码,目前只显示最便宜的产品,供应商和金额。我怎样才能找到最便宜的供应商?

SELECT Tb_Product.Name, Tb_Supplier.Name, Tb_Offers.Price as 'Price'
FROM Tb_Product, Tb_Supplier, Tb_Offers
WHERE Tb_Product.Prod_ID = Tb_Offers.Prod_ID
  AND Tb_Offers.Supp_ID = Tb_Supplier.Supp_ID
  AND Tb_Offers.Price = (SELECT Min(Tb_Offers.Price)
                        FROM Tb_Offers)

由于

1 个答案:

答案 0 :(得分:0)

假设某个产品由多个供应商提供,并且每个供应商提供多种产品,我们都遵循架构。

declare @prod table(id int, name varchar(50))
declare @supplier table(id int, name varchar(50))
declare @offer table(prodId int, supplierId int, price float)

--populate tables
insert @prod (id,name) values
(1,'A'),(2,'B'),(3,'C')

insert @supplier (id,name) values
(1,'A'),(2,'B'),(3,'C')

insert @offer(prodId,supplierId,price) values
(1,1,10),(1,2,8),(2,1,12),(2,3,11),(3,1,15),(3,3,20)

-- use common table expression to sort offers by price
;with cte as (
select prodId, supplierId, price,
row_number() over(partition by prodId order by price) rn
from @offer
)
select prodId, p.name, supplierId, s.name, price --beautify with names
from cte
inner join @prod p on cte.prodId=p.id
inner join @supplier s on cte.supplierId=s.id
where rn = 1 --only first (cheapest) price

--result returned
prodId  name    supplierId  name    price
1       A       2           B       8
2       B       3           C       11
3       C       1           A       15

旁注:根据 ANSI92 ,以逗号分隔的表格语法被视为过时。 25年前