[英]mysql group by to return a the min value and get the corresponding row data
我有這樣的數據表:
- PK_table - merchantName - price - Product
- 1 - argos - 7 - 4
- 2 - comet - 3 - 4
- 1 - Dixon - 1 - 3
- 1 - argos - 10 - 4
我希望在mysql中為產品和相應的商家選擇最低價格。
我試過了:
SELECT Product, merchantName, min(price)
FROM a_table
GROUP BY product
但是返回的結果不正確,因為它選擇了第一個商家名稱,而不是MIN的相應商家。
你怎么做呢?
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
如果兩個商人具有相同的低價,低價,則將返回兩行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.