【问题标题】:Find minimum overlap of Each Status找到每个状态的最小重叠
【发布时间】:2021-09-05 05:00:37
【问题描述】:

我需要在所有组中找到状态为 Missing/Not Ready 的日期范围(只有所有组的状态为 Missing/Notready 的重叠日期范围) '''

ID.   Group.    Eff_Date.             Exp_Date           Status
1.    1             1/1/18 10:00       3/4/18 15:23       Ready
1     1             3/4/18 15:24.      7/12/18 13:54.    Not Ready
1.    1           7/12/18 13:55.   11/22/19 11:20    Missing    
1.    1.            11/22/19 11:21.   9/25/20 1:12.     Ready   
1.    1.            9/25/20 1:13       12/31/99.           Missing          

1.    2             1/1/16 10:00       2/2/17 17:20       Ready
1     2             2/2/17 17:21.      5/25/18 1:23.      Missing
1.    2           5/25/18 1:24       9/2/18 4:15         Not Ready  
1.    2            9/2/18 4:16.         6/3/21 7:04.        Missing 
1.    2            6/3/21 7:04.    12/31/99.           Ready

未就绪的输出:(以下是各组未就绪状态的日期)

5/25/18 1:24.   7/12/18 13:54 Not Ready

失踪:(以下是每组失踪的日期)

9/25/20 1:13   6/3/21 7:04    Missing

'''

注意-> 每个 ID 可以有任意数量的组。数据库是雪花

【问题讨论】:

  • 您能否分享预期的输出,从您的查询中不清楚

标签: sql datetime snowflake-cloud-data-platform sql-date-functions sqldatetime


【解决方案1】:

您可以通过反透视和计数来做到这一点。假设给定 id 的周期不重叠:

with x as (
      select eff_date as date, 1 as inc
      from t
      where status = 'Missing'
      union all
      select end_date, -1 as inc
      from t
      where status = 'Missing'
    )
select date, next_date, active_on_date
from (select date,
             sum(sum(inc)) over (order by date) as active_on_date,
             lead(date) over (order by date) as next_date
      from x
      group by date
     ) x
where active_on_date = (select count(distinct id) from t);

注意:这一次处理一个状态,这就是 this 问题所要求的。如果您想处理所有事件类型,请提出一个问题,并提供适当的示例数据、所需结果和解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多