【问题标题】:Postgres sql query to explode all the dates between start and end date for each customerPostgresql 查询以展开每个客户的开始日期和结束日期之间的所有日期
【发布时间】:2021-12-08 16:27:51
【问题描述】:

我有一个包含以下列的表格:customerIDstartdateenddate。例如:

CustomerID     startdate(mm/dd/yyyy)       Enddate(mm/dd/yyyy)
c1             10-15-2020                  10-18-2020
c2             02-20-2021                  02-25-2021
c3             12-01-2021                  12-08-2021

如何编写 SQL 查询来分别展开每个客户的开始日期和结束日期之间的所有日期?

所以预期的输出是:

CustomerID        exploedcalendardate
c1                10-15-2020
c1                10-16-2020
c1                10-17-2020
c1                10-18-2020
c2                02-20-2021
c2                02-21-2021
c2                02-22-2021
c2                02-23-2021
c2                02-24-2021
c2                02-25-2021
c3                12-01-2021
c3                12-02-2021
c3                12-03-2021
c3                12-04-2021
c3                12-05-2021
c3                12-06-2021
c3                12-07-2021
c3                12-08-2021

【问题讨论】:

标签: sql postgresql amazon-redshift


【解决方案1】:

您可以使用 generate_series() 函数来实现这一点。这里举个例子

select customerID, dd::date AS exploedcalendardate 
from customer C
JOIN LATERAL generate_series(C.startdate, c.enddate, '1 day'::interval) dd ON true

测试查询here

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多