Get the latest date from grouped MySQL data

前端 未结 7 900
一生所求
一生所求 2020-11-27 04:29

I have the following data in my database:

|NO | model | date     | 
+---+-------+----------+
|1  | bee   |2011-12-01|
|2  | bee   |2011-12-05|
|3  | bee   |2         


        
7条回答
  •  醉酒成梦
    2020-11-27 05:04

    Are you looking for the max date for each model?

    SELECT model, max(date) FROM doc
    GROUP BY model
    

    If you're looking for all models matching the max date of the entire table...

    SELECT model, date FROM doc
    WHERE date IN (SELECT max(date) FROM doc)
    

    [--- Added ---]

    For those who want to display details from every record matching the latest date within each model group (not summary data, as asked for in the OP):

    SELECT d.model, d.date, d.color, d.etc FROM doc d
    WHERE d.date IN (SELECT max(d2.date) FROM doc d2 WHERE d2.model=d.model)
    

    MySQL 8.0 and newer supports the OVER clause, producing the same results a bit faster for larger data sets.

    SELECT model, date, color, etc FROM (SELECT model, date, color, etc, 
      max(date) OVER (PARTITION BY model) max_date FROM doc) predoc 
    WHERE date=max_date;
    

提交回复
热议问题