2017-06-13 27 views
0

我想組由馬克斯(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 

請幫助我。由於提前;)

+1

那些不重複。您有一行'a.pmn_code,a.ref_period,a.SERVICE_TYPE'的每個排列。如果這不符合您的要求,那麼您的查詢中缺少一條業務規則。 – APC

回答

0
with tempChkStatus (

PMN_CODE, REF_PERIOD , SERVICE_TYPE , STATUS , UPDATED_DTM) as 
(
select 'A',   '01/2016'  ,'OI',    'I',  to_date('19/08/2016 10:54:44', 'dd/mm/yyyy hh24:mi:ss') from dual union all 
select 'A',   '01/2016'  ,'OP',    'N',  to_date('06/06/2017 15:09:55', 'dd/mm/yyyy hh24:mi:ss') from dual union all 
select 'A',   '02/2016'  ,'OT',    'I',  to_date('31/08/2016 08:37:45', 'dd/mm/yyyy hh24:mi:ss') from dual union all 
select 'A',   '02/2016'  ,'OT',    'N',  to_date('12/10/2016 11:13:56', 'dd/mm/yyyy hh24:mi:ss') from dual union all 
select 'A',   '04/2016'  ,'OI',    'I',  to_date('19/08/2016 10:54:44', 'dd/mm/yyyy hh24:mi:ss') from dual union all 
select 'A',   '04/2016'  ,'OP',    'N',  to_date('06/06/2017 15:09:55', 'dd/mm/yyyy hh24:mi:ss') from dual 
) 
select * from (
select e.*, max(updated_dtm) over (partition by ref_period) md from tempchkstatus e 
) 
where updated_dtm = md 
; 
+0

非常感謝!是工作。 :d – nettoon493

0

你只需要從GROUP BY刪除SERVICE_TYPE

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

也許''保持'後最大(s.SERVICE_TYPE)(DENSE_RANK最後爲了通過s.updated_dtm)' –

+0

感謝這麼多!是工作。 :D – nettoon493