[英]How to Get Max Date from GROUP BY - ORACLE
This is probably really basic but SQL is not my strongest skill set.这可能真的很基础,但 SQL 不是我最强的技能。 I have a basic SQL query to get the max date of the last inspection completed for a location.我有一个基本的 SQL 查询来获取某个位置上次完成检查的最大日期。 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:这给我的结果可以为每个设施_id 的每个检查类型提供最大日期,如下所示:
-------------------------------------------------
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:我想返回如下所示的结果,因为这些结果具有真正的 MAX 日期,但也显示了已完成的检查类型:
-------------------------------------------------
facility id | inspection date | inspection type
-------------------------------------------------
93 04/28/2020 FULL
94 04/28/2020 LIMITED
-------------------------------------------------
You can use keep
in an aggregation query:您可以在聚合查询中使用keep
:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.