如何使用Group by和Max(日期)多记录

时间:2017-06-13 12:10:16

标签: sql oracle datetime group-by max

我希望每个记录由Max(Datetime)分组。但我查询有dupplicatate记录。我希望不要重复记录。

SQL:

select   a.pmn_code,
           a.ref_period,
           a.SERVICE_TYPE,
           min(a.status) keep (dense_rank last order by a.updated_dtm) as status,
           max(a.updated_dtm) as updated_dtm
  from     tempChkStatus a
  group by a.pmn_code, a.ref_period, a.SERVICE_TYPE

数据表tempChkStatus:

PMN_CODE | REF_PERIOD  | SERVICE_TYPE    | STATUS | UPDATED_DTM
A        | 01/2016     | OI              | I      | 19/08/2016 10:54:44
A        | 01/2016     | OP              | N      | 06/06/2017 15:09:55
A        | 02/2016     | OT              | I      | 31/08/2016 08:37:45
A        | 02/2016     | OT              | N      | 12/10/2016 11:13:56
A        | 04/2016     | OI              | I      | 19/08/2016 10:54:44
A        | 04/2016     | OP              | N      | 06/06/2017 15:09:55

结果SQL:

PMN_CODE | REF_PERIOD  | SERVICE_TYPE    | STATUS | UPDATED_DTM
A        | 01/2016  | OI        | I  | 19/08/2016 10:54:44
A        | 01/2016  | OP        | N  | 06/06/2017 15:09:55
A        | 02/2016  | OT        | N  | 12/10/2016 11:13:56
A        | 04/2016  | OI        | I  | 19/08/2016 10:54:44
A        | 04/2016  | OP        | N  | 06/06/2017 15:09:55

但我想要结果:

PMN_CODE | REF_PERIOD  | SERVICE_TYPE    | STATUS | UPDATED_DTM
A        | 01/2016     | OP              | N      | 06/06/2017 15:09:55
A        | 02/2016     | OT              | N      | 12/10/2016 11:13:56
A        | 04/2016     | OP              | N      | 06/06/2017 15:09:55

请帮帮我。谢谢提前;)

2 个答案:

答案 0 :(得分:0)

您只需要从SERVICE_TYPE

中删除GROUP BY即可
select s.pmn_code, s.ref_period,
       min(s.SERVICE_TYPE) as service_type,
       min(s.status) keep (dense_rank last order by s.updated_dtm) as status,
       max(s.updated_dtm) as updated_dtm
from tempChkStatus s
group by s.pmn_code, s.ref_period;

GROUP BY表达式通过聚合查询定义行返回。

此版本在MIN()上使用SERVICE_TYPE。目前尚不清楚结果集需要什么逻辑。

答案 1 :(得分:0)

ids | firstname | lastname
----+-----------+----------
1,3 | alex      | marti