how to get latest record or record with max corresponding date of all distinct values in a column in mysql?

前端 未结 5 1900
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 00:11

For Example, I have table like this:

Date      | Id | Total
-----------------------
2014-01-08  1    15
2014-01-09  3    24
2014-02-04  3    24
2014-03-15  1             


        
相关标签:
5条回答
  • 2021-01-21 00:39

    The other answers didn't work for me. I found the following code, which worked great for me:

    SELECT * FROM TABLE WHERE DATE IN (SELECT MAX(DATE) FROM TABLE)
    

    I am using SSMS 2014, SQLServer

    0 讨论(0)
  • 2021-01-21 00:46

    You can use left join as

    select 
    t1.* from table_name t1
    left join table_name t2
    on t1.Id = t2.Id and t1.Date >t2.Date
    where t2.Id is null
    

    http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

    0 讨论(0)
  • 2021-01-21 00:46

    Another way is by using INNER JOIN

    Find the latest date per ID then join result back to the table to get the value

    select A.ID,A.Date,A.value 
    from yourtable A 
    INNER JOIN 
    (
    select MAX(date) as Date,ID 
    from yourtable
    group by ID 
    ) B
    ON A.ID =B.ID and A.Date = B.Date
    
    0 讨论(0)
  • 2021-01-21 00:47

    You can also use Max() in sql:

    SELECT date, id, total
       FROM table as a WHERE date = (SELECT MAX(date)
       FROM table as b
      WHERE a.id = b.id
     )
    
    0 讨论(0)
  • 2021-01-21 00:59

    You can do it as below

    SELECT *
    FROM YourTable D
    WHERE date = (SELECT MAX(date) FROM YourTable WHERE ID = D.ID)
    
    0 讨论(0)
提交回复
热议问题