gpt4 book ai didi

sql - 如何将列添加到 generate_series 查询

转载 作者:行者123 更新时间:2023-11-29 13:02:19 24 4
gpt4 key购买 nike

查看日期范围时,generate_series 是否也返回开始日期和结束日期?

select 
'2014-06-05 00:00:00'::timestamp + ('1 month'::INTERVAL * s.a) AS date
from
generate_series(1, cast(extract(month from age('2014-09-05'::date, '2014-06-05'::date)) AS integer), 1) as s(a);

给出这个输出

date
2014-07-05 00:00:00
2014-08-05 00:00:00
2014-09-05 00:00:00

这很好,但是我想要

start_date     end_date       date
2014-06-05 2014-09-05 2014-07-05 00:00:00
2014-06-05 2014-09-05 2014-08-05 00:00:00
2014-06-05 2014-09-05 2014-09-05 00:00:00

原因是我正在从另一个表中提取多个开始/结束对,但无法找到将它们连接在一起的方法。我还在使用 PostgeSQL 8.2.15 版(因此使用了更复杂的 generate_series 函数)。

为了将其扩展到我的主要问题,我有一个包含这些开始和结束时间对的表。

    start_date         end_date
2014-08-25 00:00:00 2014-09-25 00:00:00
2014-05-16 00:00:00 2014-08-16 00:00:00
2014-09-09 00:00:00 2014-12-09 00:00:00
2014-06-05 00:00:00 2014-07-05 00:00:00
2014-05-19 00:00:00 2014-08-19 00:00:00
2014-05-15 00:00:00 2014-07-15 00:00:00
2014-09-04 00:00:00 2014-11-04 00:00:00

我如何遍历此表并将其与扩展的日期范围连接?

最佳答案

考虑升级到 current version . Postgres 8.2 早已过时并被遗忘。

对于 Postgres 8.2(或更高版本,但现代 Postgres 中有更优雅的解决方案)。

假设所有都是关于日期的,而不是时间戳。

提供 start_dateend_date 一次:

SELECT start_date, end_date
, (start_date + interval '1 month'
* generate_series(1, months))::date AS the_date
FROM (
SELECT extract(month from age(end_date, start_date))::int AS months
, start_date, end_date
FROM (SELECT '2014-06-05'::date AS start_date
, '2014-09-05'::date AS end_date
) data
) sub;

使用列名 the_date 而不是不应用作标识符的 date

改为从表 t 中提取值:

SELECT start_date, end_date
,(start_date + interval '1 month'
* generate_series(1, months))::date AS the_date
FROM (SELECT *, extract(month FROM age(end_date, start_date))::int AS months
FROM t) sub;

没有子查询

SELECT t_id, start_date, end_date
,(start_date + interval '1 month'
* generate_series(1, extract(month from age(end_date
, start_date))::int)
)::date AS the_date
FROM t;

SQL Fiddle for Postgres 8.3.

关于sql - 如何将列添加到 generate_series 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com