Postgres sql 查询以展开每个客户的开始日期和结束日期之间的所有日期

Postgres sql query to explode all the dates between start and end date for each customer

我有一个包含以下列的 table: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

您可以使用 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