Need help with Min Function in SQL
I have a table as shown below.
+------------+-------+-------+ | Date_ | Name | Score | +------------+-------+-------+ | 2012/07/05 | Jack | 1 | | 2012/07/05 | Jones | 1 | | 2012/07/06 | Jill | 2 | | 2012/07/06 | James | 3 | | 2012/07/07 | Hugo | 1 | | 2012/07/07 | Jack | 1 | | 2012/07/07 | Jim | 2 | +------------+-------+-------+
I would like to get the output like below
+------------+------+-------+ | Date_ | Name | Score | +------------+------+-------+ | 2012/07/05 | Jack | 1 | | 2012/07/06 | Jill | 2 | | 2012/07/07 | Hugo | 1 | +------------+------+-------+
When I use the MIN() function with just the date and Score column I get the lowest score for each date, which is what I want. I don’t care which row is returned if there is a tie in the score for the same date. Trouble starts when I also want name column in the output. I tried a few variation of SQL (i.e min with correlated sub query) but I have no luck getting the output as shown above. Can anyone help please:)
Query is as follows
SELECT DISTINCT
A.USername, A.Date_, A.Score
FROM TestTable AS A
INNER JOIN (SELECT Date_,MIN(Score) AS MinScore
FROM TestTable
GROUP BY Date_) AS B
ON (A.Score = B.MinScore) AND (A.Date_ = B.Date_);
Use this solution:
SQL-Fiddle Demo
This will get the minimum score per date in the
INNER JOINsubselect, which we use to join to the main table. Once we join the subselect, we will only have dates with names having the minimum score (with ties being displayed).Since we only want one name per date, we then group by
dateandscore, selecting whichever name:MIN(name).If we want to display the
namecolumn, we must use an aggregate function onnameto facilitate theGROUP BYondateandscorecolumns, or else it will not work (We could also useMAX()on that column as well).