Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Fetching lowest value

Tags:

mysql

group-by

My database structure contains columns: id, name, value, dealer. I want to retrieve row with lowest value for each dealer. I've been trying to mess up with MIN() and GROUP BY, still - no solution.

like image 841
acid Avatar asked Sep 24 '12 08:09

acid


People also ask

How do I find the lowest number in MySQL?

MySQL MIN() Function The MIN() function returns the minimum value in a set of values.

How do I find the lowest value in SQL?

The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

How do you find the lowest value in a table?

Discussion: 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.


2 Answers

Solution1:

SELECT t1.* FROM your_table t1
JOIN (
  SELECT MIN(value) AS min_value, dealer
  FROM your_table 
  GROUP BY dealer
) AS t2 ON t1.dealer = t2.dealer AND t1.value = t2.min_value

Solution2:

SELECT t1.* FROM your_table t1
LEFT JOIN your_table t2
ON t1.dealer = t2.dealer AND t1.value > t2.value
WHERE t2.value IS NULL

This problem is very famous, so there is a special page for this in Mysql's manual.

Check this: Rows Holding the Group-wise Maximum/Minimum of a Certain Column

like image 113
xdazz Avatar answered Sep 20 '22 06:09

xdazz


select id,name,MIN(value) as pkvalue,dealer from TABLENAME 
group by id,name,dealer;

here you group all rows by id,name,dealer and then you will get min value as pkvalue.

like image 31
Patriks Avatar answered Sep 22 '22 06:09

Patriks