简体   繁体   中英

How to I return a case record with latest date using SQL

I want a query that returns a record set of the shaded rows from the table above for each unique case_id by the latest data_level_assinged value. I tried something like this:

SELECT case_id, level, date_level_assigned
FROM table
SORT BY case_id, date_level_assigned DESC;

From reading it looks like I need to use an aggregate function like MAX(data_level_assinged) but am not sure how to do this.

You're almost there. Using MAX is a good approach.

SELECT b.case_id, a.level, b.date_level_assigned FROM tablename a
JOIN
    ( SELECT MAX(date_level_assigned) as date_level_assigned, case_id
    FROM tablename
    GROUP BY case_id
    ) as b
ON a.case_id = b.case_id AND a.date_level_assigned = b.date_level_assigned

You can do it in this way

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