在两个日期 Presto 之间添加行

Add rows between two dates Presto

我有一个 table,它有 3 列 - 开始、结束和 emp_num。我想为每个员工生成一个新的 table,其中包含这些日期之间的所有日期。需要使用Presto。

我引用了这个 link - inserting dates into a table between a start and end date in Presto

尝试通过创建序列使用 unnest 函数,但是,我不知道如何通过从另一个 table.

的两列中提取日期来创建序列
select unnest(seq) as t(days)
from (select sequence(start, end, interval '1' day) as seq 
      from table1)

这是 table 和预期格式

Table 1:
start       |  end         | emp_num 
2018/01/01  |   2018/01/05 | 1
2019/02/01  |   2019/02/05 | 2


Expected:
start          | emp_num 
2018/01/01     | 1
2018/01/02     | 1
2018/01/03     | 1
2018/01/04     | 1
2018/01/05     | 1
2019/02/01     | 2
2019/01/02     | 2
2019/02/03     | 2
2019/02/04     | 2
2019/02/05     | 2

这是一个可能会完成您的用例工作的查询。

逻辑是使用 Presto sequence() function 生成一个宽范围的日期(从 2000 年到 2018 年底,您可以根据需要进行调整),可以与 table 结合使用生成输出。

select dt.x, emp_num
from 
    ( select x from unnest(sequence(date '2000-01-01', date '2018-01-31')) t(x) ) dt
    inner join table1 ta on dt.x >= ta.start and dt.x <= ta.end

但是,正如 JNevill 评论的那样,创建日历 table 比每次运行查询时都即时生成日历效率更高。

它应该是一个简单的:

create table calendar as
    select x from unnest(sequence(date '1970-01-01', date '2099-01-01')) t(x);

然后您的查询将变为:

select dt.x, emp_num
from 
    calendar dt
    inner join table1 ta on dt.x >= ta.start and dt.x <= ta.end

PS :由于在野外缺少用于 Presto 的 DB Fiddles,我无法测试查询(@PiotrFindeisen - 如果你碰巧读到这个 ​​- Presto fiddle 将是很高兴有!)。