周期表(为每个更改创建行)

时间:2019-01-29 14:36:20

标签: sql oracle

我需要创建一个“周期”表,每次更新都需要一行。下表显示了两行,但ID下可以有很多分配。

我有下表:

ID  class_start class_end enroll_dt reason assignments cat_added 
 1   1/10/19     1/22/19   1/18/19  stop   1/14/19     1/10/19    
 1   1/10/19     1/22/19   1/18/19  stop   1/22/19     1/10/19

预期结果:

class_start class_end  start_dt   end_dt    enroll_dt  reason  assignments  cat_added      
 1/10/19               1/10/19    1/13/19                                     1/10/19                                                                                                        
 1/10/19               1/14/19    1/17/19                        1/14/19      1/10/19
 1/10/19               1/18/19    1/21/19     1/18/19            1/14/19      1/10/19
 1/10/19     1/22/19   1/22/19    12/31/9999  1/18/19  stop      1/22/19      1/10/19    

1 个答案:

答案 0 :(得分:1)

您尚未解释您要实现的业务逻辑。因此该解决方案仅仅是硬编码的从发布数据导出的一些规则即可。

它使用connect by level从一个输入行中产生多行(本例为基于double的子查询),并测试level有条件地填充结果集中的列。

with cte as (
         select to_date( '1/7/19', 'MM/DD/YY') as class_start,
                to_date( '1/14/19', 'MM/DD/YY') as class_end,
                to_date( '1/9/19', 'MM/DD/YY') as enroll_dt,
                'early' as reason 
         from dual
) 
select cte.class_start
        , case when level = 3 then cte.class_end 
          end as class_end
        , case when level = 1 then cte.class_start
               when level = 2 then cte.enroll_dt
               else cte.class_end - 1
          end as st_dt
        , case when level = 1 then cte.enroll_dt - 1
               when level = 2 then cte.class_end 
               else date '9999-12-31'
          end as end_dt
        , case when level > 1 then cte.enroll_dt end as enroll_dt 
        , case when level = 3 then cte.reason end as reason
from cte
connect by level <= 3
/  

最大的麻烦可能是如果您有多个输入行。在这种情况下,您将需要一个标识来将生成的行链接在一起。大概您的实际表具有某种标识符。