将用于统计生成的多个选择合并到结果集中

Combine multiple selects for statistics generation into on result set

大家好,

远方SQL,希望大家多多指教。

目前我们使用 python 汇总数据,我会尽可能将其切换为。 (SQL (Postgresql 服务器)

我的目标是让一个语句为特定时间间隔 (1 Hour, 1 Day, 1 Week, Overall) 的两个单独列生成平均值,还应计算每个时间段内的所有事件。

我可以为每个时间间隔创建 4 个单一的语句,但我不知道如何将这四个选择组合到结果集中。

select 
    count(id) as hour_count,
    camera_name,
    round(avg("pconf")) as hour_p_conf,
    round(avg("dconf")) as hour_d_conf
from camera_events where timestamp between NOW() - interval '1 HOUR' and NOW() group by camera_name;


select 
    count(id) as day_count,
    camera_name,
    round(avg("pconf")) as day_p_conf,
    round(avg("dconf")) as day_d_conf
from camera_events where timestamp between NOW() - interval '1 DAY' and NOW() group by camera_name;

select 
    count(id) as week_count,
    camera_name,
    round(avg("pconf")) as week_p_conf,
    round(avg("dconf")) as week_d_conf
from camera_events where timestamp between NOW() - interval '1 WEEK' and NOW() group by camera_name;

select 
    count(id) as overall_count,
    camera_name,
    round(avg("pconf")) as overall_p_conf,
    round(avg("dconf")) as overall_d_conf
from camera_events group by camera_name;

如果可能,结果应该类似于图像上的数据

一些提示会很好,谢谢你

最简单的方法就是加入他们。例如:

select
  coalesce(h.camera_name, d.camera_name, w.camera_name) as camera_name
  h.hour_count, h.hour_p_conf, h.hour_d_conf
  d.day_count, d.day_p_conf, d.day_d_conf
  w.week_count, w.week_p_conf, w.week_d_conf
from (
  -- hourly query here
) h
full join (
  -- daily query here
) d on d.camera_name = h.camera_name
full join (
  -- weekly query here
) w on w.camera_name = coalesce(h.camera_name, d.camera_name)

通过将 WHERE 逻辑移动到 SELECT 中的 CASE 语句来考虑条件聚合。或者,在 PostgreSQL 中使用 FILTER 子句。

select 
    camera_name,
    count(id) filter(timestamp between NOW() - interval '1 HOUR' and NOW()) as hour_count,   
    round(avg("pconf") filter(timestamp between NOW() - interval '1 HOUR' and NOW())) as hour_p_conf,
    round(avg("dconf") filter(timestamp between NOW() - interval '1 HOUR' and NOW())) as hour_d_conf,
    count(id) filter(timestamp between NOW() - interval '1 DAY' and NOW()) as day_count,
    round(avg("pconf") filter(timestamp between NOW() - interval '1 DAY' and NOW())) as day_p_conf,
    round(avg("dconf") filter(timestamp between NOW() - interval '1 DAY' and NOW())) as day_d_conf,
    count(id) filter(timestamp between NOW() - interval '1 WEEK' and NOW()) as week_count,
    round(avg("pconf") filter(timestamp between NOW() - interval '1 WEEK' and NOW())) as week_p_conf,
    round(avg("dconf") filter(timestamp between NOW() - interval '1 WEEK' and NOW())) as week_d_conf,
    count(id) as overall_count,
    round(avg("pconf")) as overall_p_conf,
    round(avg("dconf")) as overall_d_conf
from camera_events
group by camera_name;