【问题标题】:Oracle: How to use Group by and Max(datetime) each record no duplicationOracle:如何使用 Group by 和 Max(datetime) 每条记录不重复
【发布时间】:2017-06-07 15:15:10
【问题描述】:

我想在每条记录中按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

【问题讨论】:

  • 请去掉多余的标签。 MS sql不能同时是Oracle。
  • 我不明白为什么您需要在 Select from temp 语句中使用 Where 子句,因为您的 CTE 中已经有了数据。

标签: sql oracle datetime group-by max


【解决方案1】:

你应该只按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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多