我有以下pg脚本
preferenceKeeper?.user?.weightValue.toString().toDouble()
运行上面提到的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';
如何在右连接中编写'for循环'以避免多个'union all',如此
select * from ended_jobs()
答案 0 :(得分:2)
您可以使用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