Return value at max date for a particular id

前端 未结 3 354
清歌不尽
清歌不尽 2021-01-03 02:54

Here\'s my sql server table

ID       Date       Value 
___      ____       _____
3241     9/17/12    5
3241     9/16/12    100
3241     9/15/12    20
4355           


        
相关标签:
3条回答
  • 2021-01-03 03:05

    This would give you what you need:

    SELECT 
        m.ID,
        m.Date,
        m.Value
    FROM 
        myTable m
        JOIN (SELECT ID, max(Date) as Date FROM myTable GROUP BY ID) as a
        ON m.ID = a.ID and m.Date = a.Date
    
    0 讨论(0)
  • 2021-01-03 03:14

    You can use the following:

    select t1.id, t2.mxdate, t1.value
    from yourtable t1
    inner join
    (
      select max(date) mxdate, id
      from yourtable
      group by id
    ) t2
      on t1.id = t2.id
      and t1.date = t2.mxdate
    

    See Demo

    0 讨论(0)
  • 2021-01-03 03:17

    You haven't specified your SQL implementation, but something like this should work:

    Note that the op didn't specifically ask to use max(), just to get the id, value at the max[imum] date.

    TSQL:

    select top 1 ID, Date, Value from yourtable order by Date DESC;
    

    Not TSQL, has to support limit: (Not tested.)

    select ID, Date, Value from yourtable order by Date DESC limit 1,1;
    
    0 讨论(0)
提交回复
热议问题