简体   繁体   中英

SQL return most recent date & time stamp

I have the below data and need to see the most recent date where the action equals 'USED':

CAT STAMP               ACTION
A   05/12/2019 00:13    USED
A   05/12/2019 07:56    USED
A   05/12/2019 09:05    NEW
A   05/12/2019 10:46    NEW
B   20/12/2019 20:50    USED
B   13/01/2020 14:50    USED
B   10/01/2020 22:39    NEW
B   05/12/2019 12:04    NEW

For the above I would need it to return:

A   05/12/2019 07:56    USED
B   13/01/2020 14:50    USED

For each 'Cat' there could be hundreds of entries for each day and it needs to look back over several years, returning only the most recent entry. Have tried MAX function but don't think it works due to the date format.

You can use subquery:

select t.*
from table t 
where t.action = 'used' and
      t.stamp = (select max(t2.stamp) from table t1 where t1.stamp = t.stamp)

One way to do it is to filter with a correlated subquery:

select t.*
from mytable t
where 
    t.action = 'USED'
    and stamp = (
        select max(t1.stamp) 
        from mtable t1 
        where t1.cat = t.cat and t1.action = t.action
    )

Another typical solution is the anti- left join pattern:

select t.*
from mytable t
left join mytable t1
    on  t1.cat = t.cat
    and t1.action = t.action
    and t1.stamp > t.stamp
where t.action = 'USED' and t1.cat is null

Both solutions do assume that stamp is stored in a date -like datatype. If it is not, then you need an additional step to convert the string to a date.

It sounds like stamp is stored as varchar instead of datetime. Try CAST first.

SELECT cat, MAX(CAST stamp AS DateTime) as MxDate, 'used' as Action
FROM mytable
WHERE Action = 'used'
GROUP BY cat

This would be:

select t.*
from t 
where t.stamp = (select min(t2.stamp)
                 from table t2
                 where t2.cat = t.cat and t2.action = 'used' 
                );

Note the filtering is in the subquery.

Or, perhaps more simply as:

select t.cat, max(t.stamp)
from t
where t.action = 'used'
group by t.cat;

However, this does not allow you to return other columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM