在 Redshift 中按秒创建时间戳列表

Create list of timestamps by second in Redshift

简介: 我需要在 Redshift 中创建一个 table,它是从今天开始双向一年中所有秒数的时间戳列表。

条件:

我愿意,但不需要:

示例所需输出:

2021-09-13 00:01:04.000000
2021-09-13 00:01:03.000000
2021-09-13 00:01:02.000000
2021-09-13 00:01:01.000000
2021-09-13 00:01:00.000000

有没有办法使用某种 for 循环或 n+1 类型的解决方案来做到这一点?我非常愿意在 Epoch 时间执行此操作,然后像上面那样转换为 timestamp 类型,我只需要一个可行的解决方案,允许我写入 table。生成示例输出的代码如下:

with interval_1_second_cte as (
    SELECT CURRENT_DATE::TIMESTAMP - (i * interval '1 seconds') as interval_1_second
    FROM generate_series(1, (365 * 24 * 60 * 60)) i
    UNION ALL
    SELECT CURRENT_DATE::TIMESTAMP + (i * interval '1 seconds') as interval_1_second
    FROM generate_series(1, (365 * 24 * 60 * 60)) i
)

select top 5 i1sc.interval_1_second
from interval_1_second_cte i1sc
where interval_1_second like '2021-09-13 00:01:0%'
order by 1;

除了当年所有秒数的列表,我不明白“双向”是什么意思。

这可以使用递归通用 table 表达式来实现:

with recursive this_year as (
    SELECT date_trunc('year', current_timestamp) as ts
    UNION ALL
    SELECT p.ts + interval '1 second'
    from this_year p
    where p.ts < date_trunc('year', current_timestamp) + interval '1 year'
)
select *
from this_year