簡體   English   中英

Oracle:如何使用Group by和Max(datetime)每個記錄都沒有重復

[英]Oracle: How to use Group by and Max(datetime) each record no duplication

我想在每個記錄中按Max(Datetime)分組,但是查詢中有重復的記錄。 我不要重復的記錄。

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

恢復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

但我想要結果:

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

您只ref_period分組,為什么還要按status分組? 而是按ref_period ,選擇max(update_dtm) ,然后-也要獲取status -使用LAST函數(如果您不熟悉它,請參閱文檔)。 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM