【问题标题】:Oracle SQL: Compare Date Ranges and get the dates of the same dayOracle SQL:比较日期范围并获取同一天的日期
【发布时间】:2018-09-27 08:53:57
【问题描述】:

我有不同的事件:

如果一天中发生了 2 次以上,我想知道是哪些以及有多少。 如何构建 SQL 命令?

预期输出:

同一天有 2 个以上的活动。

【问题讨论】:

  • 将您的示例数据和预期输出作为纯文本而不是图像发布。
  • 结果中如何预期事件 ID 181? Date_from 和 Data_until 不是 27..请解释
  • 请提供样品

标签: sql database oracle date


【解决方案1】:

试试这个:

    WITH calendar
     AS (    SELECT TRUNC( SYSDATE - LEVEL ) AS cal_day
               FROM DUAL
         CONNECT BY LEVEL < 30)
  SELECT calendar.cal_day,
         COUNT( e.event_id ) AS number_of_events,
         LISTAGG( e.event_id, ', ' ) WITHIN GROUP (ORDER BY e.date_from)
            AS events
    FROM calendar, event e
   WHERE calendar.cal_day BETWEEN e.date_from AND e.date_until
GROUP BY calendar.cal_day
  HAVING COUNT( e.event_id ) > 1;

您可以随时更改CONNECT BY LEVEL &lt; :n 中的数字或将日历具体化为表格。

【讨论】:

    【解决方案2】:

    样本输入:

    create table ns_123(a int,b date,c date);
    
    insert into ns_123 values(179,'27-sep-2018','27-sep-2018');
    
    insert into ns_123 values(181,'26-sep-2018','28-sep-2018');
    
    insert into ns_123 values(180,'27-sep-2018','27-sep-2018');
    
    select * from ns_123;
    
    select distinct n1.a from  ns_123 n1,ns_123 n2 where  (n1.b-n2.b)>=(n1.c-n2.c);
    

    样本输出:

    179
    180
    181
    

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 2022-06-29
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多