I want to Group by Max(Datetime)
in each record, but my query has duplicate records. I don't want duplicate records.
SQL:
with temp as
(
SELECT a.ref_period, b.status, a.updated_dtm
FROM ir_net_cndn_detail a,ir_net_cndn b
WHERE a.bill_no=b.bill_no
AND b.company_code = a.company_code
AND TO_DATE(a.ref_period,'MM/yyyy') >= TO_DATE(&p_ref_period_start,'MM/yyyy')
AND TO_DATE(a.ref_period,'MM/yyyy') <= TO_DATE(&p_ref_period_end,'MM/yyyy')
)
select a.ref_period, a.status, max(updated_dtm) as updated_dtm
from temp a
where TO_DATE(a.ref_period,'MM/yyyy') >= TO_DATE(&p_ref_period_start,'MM/yyyy')
AND TO_DATE(a.ref_period,'MM/yyyy') <= TO_DATE(&p_ref_period_end,'MM/yyyy')
group by a.ref_period, a.status
Resut SQL:
ref_period | status | update_dtm
01/2015 | I | 01/09/2016 13:29:56
01/2015 | I | 18/05/2017 17:01:52
01/2015 | I | 18/05/2017 16:16:23
07/2015 | I | 01/09/2016 13:29:56
07/2015 | I | 07/01/2016 10:17:39
08/2015 | I | 01/09/2016 13:29:56
09/2015 | N | 05/06/2017 15:59:55
09/2015 | I | 01/09/2016 13:29:56
10/2015 | I | 01/09/2016 13:29:56
But I want Result:
ref_period | status | update_dtm >> I want max(update)/1 record with no duplication
01/2015 | I | 18/05/2017 17:01:52
07/2015 | I | 01/09/2016 13:29:56
08/2015 | I | 01/09/2016 13:29:56
09/2015 | N | 05/06/2017 15:59:55
10/2015 | I | 01/09/2016 13:29:56
You should only group by ref_period
, why are you also grouping by status
? Rather, group by ref_period
, select max(update_dtm)
, and - to get the status
as well - use the LAST
function (see the documentation if you are not familiar with it). https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm
...
select ref_period,
min(status) keep (dense_rank last order by update_dtm) as status,
max(update_dtm) as update_dtm
from temp
group by ref_period
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.