Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to select distinct row with minimum value

I want an SQL statement to get the row with a minimum value.

Consider this table:

id  game   point 1    x      5 1    z      4 2    y      6 3    x      2 3    y      5 3    z      8 

How do I select the ids that have the minimum value in the point column, grouped by game? Like the following:

id  game   point     1    z      4 2    y      5 3    x      2    
like image 210
balaji Avatar asked Mar 08 '13 10:03

balaji


People also ask

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

To select data where a field has min value, you can use aggregate function min(). The syntax is as follows. SELECT *FROM yourTableName WHERE yourColumnName=(SELECT MIN(yourColumnName) FROM yourTableName);

How do you select a 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.

How do I select only unique rows in SQL?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

How do I select a minimum length in SQL?

SQL Server databases use LEN or DATALENGTH to find field width. It also has its own function to find the maximum length of a column – COL_LENGTH. SELECT MIN(LENGTH(<column_name>)) AS MinColumnLength FROM Table; If we include any non-aggregate functions into our query then we need a GROUP BY clause.


2 Answers

Use:

SELECT tbl.* FROM TableName tbl   INNER JOIN   (     SELECT Id, MIN(Point) MinPoint     FROM TableName     GROUP BY Id   ) tbl1   ON tbl1.id = tbl.id WHERE tbl1.MinPoint = tbl.Point 
like image 185
Ken Clark Avatar answered Sep 28 '22 06:09

Ken Clark


This is another way of doing the same thing, which would allow you to do interesting things like select the top 5 winning games, etc.

 SELECT *  FROM  (      SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Point) as RowNum, *      FROM Table  ) X   WHERE RowNum = 1 

You can now correctly get the actual row that was identified as the one with the lowest score and you can modify the ordering function to use multiple criteria, such as "Show me the earliest game which had the smallest score", etc.

like image 28
Shiroy Avatar answered Sep 28 '22 07:09

Shiroy