这是我正在使用的当前SQL查询:
SELECT Merchant.Product, Merchant.Name, Merchant.Price
FROM a_table AS Merchant
JOIN
(
SELECT Product, MIN(Price) AS MinPrice
FROM a_table
GROUP BY Product
) AS Price
ON Merchant.Product = Price.Product
AND Merchant.Price = Price.MinPrice
从此数据集:
Product Name Price
11 Merch1 19.00
11 Merch2 20.00
11 Merch3 19.00
11 Merch4 19.50
12 Merch1 20.00
12 Merch2 20.00
13 Merch1 17.00
13 Merch3 15.00
当价格相同时,当前SQL输出多个产品记录,如下所示:
Product Name Price
11 Merch1 19.00
11 Merch3 19.00
12 Merch1 20.00
12 Merch2 20.00
13 Merch3 15.00
我想按产品分组并显示最低价格和相应的行数据。如果产品的两个价格相同,请使用找到的第一条记录。
尝试获得此结果:
Product Name Price
11 Merch1 19.00
12 Merch1 20.00
13 Merch3 15.00
最佳答案
您不需要任何连接即可执行此操作。
如果您希望通过商家获取每种产品的最低价格,则可以执行以下操作:
SELECT Product, Name, MIN(Price) as MinPrice
FROM a_table
GROUP BY Product, Name
如果您只是想要某产品的最低价格,而不考虑其商家,则可以执行以下操作:
SELECT Product, MIN(Price) as MinPrice
FROM a_table
GROUP BY Product