Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql group by to return a the min value and get the corresponding row data

Tags:

sql

mysql

I have a table of data like so :

- PK_table - merchantName - price - Product
- 1        - argos        - 7     - 4
- 2        - comet        - 3     - 4
- 1        - Dixon        - 1     - 3
- 1        - argos        - 10    - 4

I wish to select the minimum price for a product and the corresponding merchant in mysql.

I tried:

SELECT Product, merchantName, min(price)
FROM a_table
GROUP BY product

however the result returned is incorrect since it chooses the first merchant name and not the corresponding merchant of the MIN.

how do you do it?

like image 460
thiswayup Avatar asked Nov 25 '09 19:11

thiswayup


People also ask

How do I SELECT a row with minimum value in SQL?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.

Can we use group by with where clause in MySQL?

GROUP BY: This requires one (or multiple) column names based on which we want the results to be aggregated. [HAVING condition]: This is an optional condition that could be specified for SELECT queries that use the GROUP BY clause. It's similar to a WHERE clause in a normal SELECT query.

How do I find the smallest value in MySQL?

The MIN() function in MySQL is used to return the minimum value in a set of values from the table. It is an aggregate function that is useful when we need to find the smallest number, selecting the least expensive product, etc.

What clause groups a set of rows into a set of summary rows by values of columns or expressions?

A SELECT statement clause that divides the query result into groups of rows, usually for the purpose of performing one or more aggregations on each group. The SELECT statement returns one row per group.


1 Answers

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

Will return two rows if two merchants have the same low, low price.

like image 123
Larry Lustig Avatar answered Sep 30 '22 06:09

Larry Lustig