我正在尝试查询sql数据库表以获取产品的最低价格。我还想获取一个额外的列,其中包含具有最低价格的行的值。我的数据看起来像这样。
ProductId | Price | Location
1 | 50 | florida
1 | 55 | texas
1 | 53 | california
2 | 65 | florida
2 | 64 | texas
2 | 60 | new york
我可以通过此查询查询产品的最低价格
select ProductId, Min(Price)
from Table
group by ProductId
我想做的是在上面的查询中包括从中查询最小价格的位置。有没有标准的方法来实现这一点?
一种方法使用相关的子查询:
select t.*
from t
where t.price = (select min(t2.price) from t t2 where t2.productid = t.productid);
在大多数数据库中,这在索引(productid, price)
上具有非常好的性能。