简体   繁体   中英

How to Get Max Date from GROUP BY - ORACLE

This is probably really basic but SQL is not my strongest skill set. I have a basic SQL query to get the max date of the last inspection completed for a location. I also want to know what type of inspection it was.

So far I have this:

SELECT
        facility_id
        ,max(inspection_date) as last_inspection
        ,inspection_type
    FROM facility_inspections
    GROUP BY facility_id  ,inspection_type

which gives me results that can have max dates for each inspection type for each each facility_id like this:

-------------------------------------------------
facility id | inspection date | inspection type 
-------------------------------------------------
93              04/28/2020        FULL
93              05/16/2018        VISIT
94              04/28/2020        LIMITED
94              06/12/2014        FULL
-------------------------------------------------

I want to return results that look like the follow because those have the true MAX date but also shows me the type of inspection that was completed:

-------------------------------------------------
facility id | inspection date | inspection type 
-------------------------------------------------
93              04/28/2020        FULL
94              04/28/2020        LIMITED
-------------------------------------------------

You can use keep in an aggregation query:

SELECT facility_id, max(inspection_date) as last_inspection,
       max(inspection_type) keep (dense_rank first order by inspection_date desc)
FROM facility_inspections
GROUP BY facility_id;

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