在Snowflake View中将日期范围划分为新记录

问题描述

我有一个包含开始日期和结束日期的表,我需要将记录拆分为逐日记录,并且需要在视图中显示

| PersonID  | CompanyID    | Start_DT    | End_DT    |
|-----------|--------------|-------------|-----------|
| A12       | abc          | 05-01-2020  | 05-03-2020|
| B23       | def          | 06-08-2020  | 06-14-2020|

| PersonID  | CompanyID    | New_DT      |
|-----------|--------------|-------------|
| A12       | abc          | 05-01-2020  | ==> A12 Start Date is 05-01-2020 and End Date is 05-03-2020. So there are 3 records generated in New_DT
| A12       | abc          | 05-02-2020  | 
| A12       | abc          | 05-03-2020  | 
| B23       | def          | 06-08-2020  | 
| B23       | def          | 06-09-2020  | 
| B23       | def          | 06-10-2020  | 
| B23       | def          | 06-11-2020  | 
| B23       | def          | 06-12-2020  | 
| B23       | def          | 06-13-2020  | 
| B23       | def          | 06-14-2020  |   

如何在View中实现这一目标?

解决方法

您可以使用递归CTE:

with cte as (
      select PersonID,CompanyID,Start_DT as new_dt,End_DT  
      from t
      union all
      select PersonID,dateadd(day,1,new_dt),End_DT  
      from cte
      where new_dt < end_dt
     )
select PersonID,new_dt
from cte
option (maxrecursion 0);

如果期限超过100天,则需要添加option (maxrecursion 0)

Here是db 小提琴。

,

要填写日期,需要一种方法来生成行。一种tally或数字表是一种快速有效的方法。像这样

tally tvf(产生足够多的行,足以填充BIGINT)

ARIMA(1,0)(1,0)[12] with drift

查询

forecast::auto.arima

输出

drop function if exists [dbo].[fnNumbers];
go
create function [dbo].[fnNumbers](
  @zero_or_one   bit,@n             bigint)
returns table with schemabinding as return
with n(n) as (select null from (values (1),(2),(3),(4)) n(n))
select 0 n where @zero_or_one = 0
union all
select top(@n) row_number() over(order by (select null)) n
from n na,n nb,n nc,n nd,n ne,n nf,n ng,n nh,n ni,n nj,n nk,n nl,n nm,n np,n nq,n nr;
go