自然数
来自 PostgreSQL 维基
跳转到导航跳转到搜索
拥有一个自然数的来源来连接(例如,生成某种序列)可能很有用。
我知道两种创建此类来源的方法
视图
create or replace view nats as
select row_number() over (order by 1) as n
from (select 1 union select 2) t1
join (select 1 union select 2) t2
join (select 1 union select 2) t3
join (select 1 union select 2) t4
join (select 1 union select 2) t5
...
根据需要添加更多行。t-数字是视图生成的行的 2 的幂数,例如 t5 将生成 32 行 (2^5)。
函数
使用函数作为数字来源似乎比视图略快,但更重要的是,没有生成数量的限制。
create or replace function nats(numeric) returns setof numeric as
$$
-- return a table of ints from 0 to specified limit.
-- usage:
-- select nats(4096) as n;
declare
i numeric;
begin
for i in 0..$1 loop
return next i;
end loop;
return;
end;
$$
language 'plpgsql' immutable strict;
我使用 nats 函数来生成日期间隔序列,如下所示
select
start_time
, end_time
, period_start_ts
, period_end_ts
from (
select
CAST('1970-01-01' AS TIMESTAMP WITHOUT TIME ZONE) + CAST(CAST(period_start_ts AS VARCHAR) || ' s' AS INTERVAL) AS start_time
, CAST('1970-01-01' AS TIMESTAMP WITHOUT TIME ZONE) + CAST(CAST(period_end_ts AS VARCHAR) || ' s' AS INTERVAL) AS end_time
, period_start_ts
, period_end_ts
from (
select
:start_ts + n * :period_len_secs as period_start_ts
, :start_ts + (n + 1) * :period_len_secs as period_end_ts
from (select nats(50000) as n) nats
) nats
where period_end_ts <= :end_ts
) dates