为每个 id 生成日期

Generating dates for each id

我有一个包含 3 列的 table。我想为每个 ID 创建一个日期列,从 start_dateend_date,如果没有 end_date 则到今天。

如何在 Postgres 中激活它?谢谢!

样本table:

+------+------------+------------+--+
|  id  | start_date |  end_date  |  |
+------+------------+------------+--+
| 47ef | 2020-09-25 | 2020-09-30 |  |
| b67c | 2020-09-21 | 2020-10-02 |  |
| 9f9e | 2020-08-28 | 2020-10-02 |  |
| 854a | 2020-07-29 | 2020-10-05 |  |
| a316 | 2020-05-01 | NULL       |  |
+------+------------+------------+--+

id '47ef' 的期望输出:

+------+------------+------------+------------+
|  id  | start_date |  end_date  |    date    |
+------+------------+------------+------------+
| 47ef | 2020-09-25 | 2020-09-30 | 2020-09-25 |
| 47ef | 2020-09-25 | 2020-09-30 | 2020-09-26 |
| 47ef | 2020-09-25 | 2020-09-30 | 2020-09-27 |
| 47ef | 2020-09-25 | 2020-09-30 | 2020-09-28 |
| 47ef | 2020-09-25 | 2020-09-30 | 2020-09-29 |
| 47ef | 2020-09-25 | 2020-09-30 | 2020-09-30 |
+------+------------+------------+------------+

你确实可以使用 generate_series():

select t.id, t.start_date, t.end_date, g.dt::date
from the_table t
    cross join lateral generate_series(t.start_date, coalesce(t.end_date, current_date), interval '1 day') as g(dt)
order by t.id, g.dt