I have the following data in my database:
|NO | model | date |
+---+-------+----------+
|1 | bee |2011-12-01|
|2 | bee |2011-12-05|
|3 | bee |2011-12-12|
|4 | tar |2011-12-13|
I want to get the latest date of each model group:
| model | date |
+-------+----------+
| bee |2011-12-12|
| tar |2011-12-13|
I tried:
SELECT model, date
FROM doc
WHERE date ........????? //what is the next?
GROUP BY model
This question is related to
mysql
sql
date
greatest-n-per-group
Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:
SELECT model, date
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model
Subquery giving dates. We are not linking with the model. So below query solves the problem.
If there are duplicate dates/model can be avoided by the following query.
select t.model, t.date
from doc t
inner join (select model, max(date) as MaxDate from doc group by model)
tm on t.model = tm.model and t.date = tm.MaxDate
This should work:
SELECT model, date FROM doc GROUP BY model ORDER BY date DESC
It just sort the dates from last to first and by grouping it only grabs the first one.
You can try using max() in subquery, something like this :
SELECT model, date
FROM doc
WHERE date in (SELECT MAX(date) from doc GROUP BY model);
And why not to use this ?
SELECT model, date FROM doc ORDER BY date DESC LIMIT 1
try this:
SELECT model, date
FROM doc
WHERE date = (SELECT MAX(date)
FROM doc GROUP BY model LIMIT 0, 1)
GROUP BY model
Source: Stackoverflow.com