【问题标题】:Add rows between two dates Presto在两个日期之间添加行 Presto
【发布时间】:2019-06-15 06:40:42
【问题描述】:

我有一个包含 3 列的表 - start、end 和 emp_num。我想生成一个新表,其中包含每个员工的这些日期之间的所有日期。需要使用 Presto。

我参考了这个链接 - inserting dates into a table between a start and end date in Presto

尝试通过创建序列来使用 unnest 函数,但是,我不知道如何通过从另一个表的两列中提取日期来创建序列。

select unnest(seq) as t(days)
from (select sequence(start, end, interval '1' day) as seq 
      from table1)

这是表格和预期格式

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

【问题讨论】:

  • 创建一个包含所有日期的新表。假设表名为“日历”,列名为“mydate”,您可以执行SELECT calendar.mydate, emp_num FROM table1 INNER JOIN calendar ON calendar.mydate BETWEEn table1.start and table1.end;
  • @JNevill:我很难创建日历表。我的原始数据有 150 多年的历史。你能告诉我如何创建这个日历表吗?我事先不知道开始和结束日期,这些是以编程方式生成并填充到 table1
  • Check out this answer which generates sequences of dates on the fly。那只是在快速搜索之后,所以我敢打赌 prestodb 会有更多技术。
  • @JNevill:谢谢。我之前提到过该链接,但似乎无法正确获得 presto 等价物(特别是对于 dateadd 函数),这就是我发布问题的原因。感谢您的回复
  • 明白了。我希望我有一个 prestodb 盒子可以放屁,看看我能不能给你一个更好的答案。仅仅在excel中列出日期并导入只是为了设置日历表可能是值得的。它们在任何数据库中都非常有用。

标签: sql presto


【解决方案1】:

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

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

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 所评论的那样,创建日历表比在每次运行查询时即时生成它更有效。

应该很简单:

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 会很高兴!)。

【讨论】:

  • 我喜欢数据库小提琴的想法!
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 2019-09-23
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多