这张桌子是什么样子的:
------------------------------------------------------------------------
ProductId ProductType SupplierId Price Date
10001 Toy1 3 20 2011-10-20
10001 Toy1 5 23 2011-11-29
10002 Book1 3 20 2010-12-29
10004 Book2 4 12 2013-2-11
10004 Book2 3 25 2014-1-1
10004 Book2 5 23 2012-9-18我需要一个查询来获得每个供应商的最低价格的产品,所以在上面的表上运行查询后的结果是:
----------------------------------
SupplierId ProductType
3 Toy1
3 Book1
4 Book2
5 Toy1
5 Book2谢谢。
发布于 2014-11-25 22:30:57
您可以使用where子句或聚合中的子查询和连接来完成此操作:
select t.*
from table t
where t.price = (select min(price)
from table t2
where t2.supplierid = t.supplierid
);编辑:
具有聚合的版本是:
select t.*
from table t join
(select supplierId, min(price) as minprice
from table t
group by supplierId
) ts
on ts.supplierId = t.supplierId and ts.minprice = t.price;在某些情况下,这可能比以前的版本表现得更好。如果性能在较大的表上是一个问题,那么在您的环境中测试这两种性能以及适当的索引都是很重要的。
发布于 2014-11-25 22:45:39
SELECT a.SupplierID, a.ProductType
FROM table a
WHERE NOT EXISTS (SELECT * FROM table b WHERE b.SupplierID = a.SupplierID and b.Price < a.Price)https://stackoverflow.com/questions/27137943
复制相似问题