【问题标题】:Partition rows where dates are between the previous dates日期在先前日期之间的分区行
【发布时间】:2019-04-01 14:23:46
【问题描述】:

我有下表。

我想确定 start_date 和 end_date 的重叠间隔。

*edit 我想删除那些行重叠的开始日期和结束日期之间天数最少的行。

例子:

pgid 1 & pgid 2 have overlapping days. Remove the row that has the least amount of days between start_date and end_date.

表 A

id   pgid  Start_date    End_date      Days
 1    1    8/4/2018      9/10/2018      37
 1    2    9/8/2018      9/8/2018        0
 1    3    10/29/2018    11/30/2018     32
 1    4    12/1/2018     sysdate        123    

预期结果:

 id   Start_date    End_date     Days
 1     8/4/2018      9/10/2018    37 
 1     10/29/2018    11/30/2018   32  
 1     12/1/2018     sysdate      123    

【问题讨论】:

    标签: sql oracle window-functions


    【解决方案1】:

    我在想exists:

    select t.*,
           (case when exists (select 1
                              from t t2
                              where t2.start_date < t.start_date and
                                    t2.end_date > t.end_date and
                                    t2.id = t.id 
                             )
                 then 2 else 1
            end) as overlap_flag
    from t;
    

    【讨论】:

    • @MrJohn 。 . .您是否有理由不接受此答案?
    • 不确定答案是否满足我的需求。我目前正在更详细地审查。
    【解决方案2】:

    也许lead 和lag:

    SELECT 
    CASE 
    WHEN END_DATE > LEAD (START_DATE) OVER (PARTITION BY id ORDER BY START_DATE) THEN 1
    WHEN START_DATE < LAG (END_DATE) OVER (PARTITION BY id ORDER BY START_DATE) THEN 1 
    ELSE 0
    END OVERLAP_FLAG
    FROM A
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2013-01-31
      相关资源
      最近更新 更多