gpt4 book ai didi

postgresql - pg 函数内的 for 循环

转载 作者:行者123 更新时间:2023-11-29 14:31:54 24 4
gpt4 key购买 nike

我有以下pg脚本

create or replace function ended_jobs()
returns table(
"Time Range" timestamptz,
"Ended Jobs" numeric
) as $$
begin
return query SELECT date_trunc('HOUR',date_interval) as "Time Range", sum(COALESCE(end_count,0)) "Ended Jobs"
FROM "job_start_end_rollups"
right join ( (select current_timestamp - interval '0 HOUR' date_interval)
union all (select current_timestamp - interval '1 HOUR' date_interval)
union all (select current_timestamp - interval '2 HOUR' date_interval)
union all (select current_timestamp - interval '3 HOUR' date_interval)
union all (select current_timestamp - interval '4 HOUR' date_interval)
union all (select current_timestamp - interval '5 HOUR' date_interval)
union all (select current_timestamp - interval '6 HOUR' date_interval)
union all (select current_timestamp - interval '7 HOUR' date_interval)
union all (select current_timestamp - interval '8 HOUR' date_interval)
union all (select current_timestamp - interval '9 HOUR' date_interval)
union all (select current_timestamp - interval '10 HOUR' date_interval)
union all (select current_timestamp - interval '11 HOUR' date_interval)
union all (select current_timestamp - interval '12 HOUR' date_interval)
union all (select current_timestamp - interval '13 HOUR' date_interval)
union all (select current_timestamp - interval '14 HOUR' date_interval)
union all (select current_timestamp - interval '15 HOUR' date_interval) )
date_intervals on date_trunc('HOUR', TIMESTAMP WITH TIME ZONE 'epoch' + chunk_start_time * interval '1 millisecond' ) = date_trunc('HOUR',date_interval)
GROUP BY date_part('HOUR',TIMESTAMP WITH TIME ZONE 'epoch' + chunk_start_time * interval '1 millisecond'),date_interval
ORDER BY date_interval LIMIT 16;
end;
$$
LANGUAGE 'plpgsql';

运行上面提到的pg脚本后我可以得到数据

select * from ended_jobs()

我怎样才能在正确的连接中写“for 循环”以避免多个“union all”,就像这样

.......
right join ( (select current_timestamp - interval '0 HOUR' date_interval)
for i in 1..16 loop
union all (select current_timestamp - concat(i,' HOUR')::INTERVAL date_interval)
end loop;
........

最佳答案

您可以为此使用generate_series():

FROM "job_start_end_rollups"  
right join generate_series(current_timestamp - interval '15 HOUR',
current_timestamp,
interval '1 hour') as date_intervals(date_interval)
ON ....

您还可以将 date_trunc() 移到其中:

right join (
select date_trunc('HOUR',di) as date_interval
from generate_series(current_timestamp - interval '15 HOUR',
current_timestamp,
interval '1 hour') as t(di)
) as date_intervals ON .... = date_intervals.date_interval

关于postgresql - pg 函数内的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481682/

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