【问题标题】:Generating dates for each id为每个 id 生成日期
【发布时间】:2021-02-13 03:20:19
【问题描述】:

我有一个包含 3 列的表格。我想为每个 id 从其 start_dateend_date 创建一个日期列,如果没有 end_date 然后到今天。

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

示例表:

+------+------------+------------+--+
|  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 |
+------+------------+------------+------------+

【问题讨论】:

  • 为什么是date 列?您已经有了日期范围; start_dateend_date

标签: postgresql generate-series


【解决方案1】:

你确实可以使用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

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2019-08-14
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多