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
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);
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With