MySQL组由min()和限制输出组成

时间:2015-11-16 21:17:57

标签: mysql group-by limit min

这是我正在使用的当前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

2 个答案:

答案 0 :(得分:2)

您不需要任何联接来执行此操作。

如果您希望商家获得每件商品的最低价格,您可以这样做:

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

答案 1 :(得分:0)

以下是最终符合我需求的查询...

http://sqlfiddle.com/#!9/c8937c/35/0

SELECT emp2.product,
       emp1.name,
       emp2.MinPrice
FROM (
  SELECT product,
     Min(price) as MinPrice
  FROM   Merchant
 GROUP BY product
) as emp2 JOIN Merchant as emp1 ON emp1.price = emp2.MinPrice
GROUP BY product;