У меня есть следующий скрипт 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 loop' внутри справаприсоединяйтесь, чтобы избежать нескольких «объединение всех», как это
.......
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;
........