select n.l_id, n.fromorto, DATE(dtime),avg(mean_speed) as ms_sat_t
from newdataa n
inner join majhwys as m
on n.l_id = m.link_id
where n.day_number=6 and n.fromorto='T'
group by n.fromorto,CAST(dtime as DATE),n.l_id
order by n.l_id
在where子句中可以有四个组合,第6/7天,以及fromorto-F / T。我必须编写4个单独的查询,有没有一种方法可以编写一个包含4列(ms_sat_f,ms_sat_t,ms_sun_f,ms_sun_t)的查询。我不太确定要编写子查询。任何帮助,将不胜感激。
答案 0 :(得分:1)
您可以将条件聚合与filter
子句一起使用:
select n.l_id, n.fromorto, DATE(dtime),
avg(mean_speed) filter (where n.day_number = 6 and n.fromorto = 'T') as ms_sat_t,
avg(mean_speed) filter (where n.day_number = 6 and n.fromorto = 'F') as ms_sat_f,
avg(mean_speed) filter (where n.day_number = 7 and n.fromorto = 'T') as ms_sun_t,
avg(mean_speed) filter (where n.day_number = 7 and n.fromorto = 'F') as ms_sun_f
from newdataa n inner join
majhwys m
on n.l_id = m.link_id
group by n.fromorto, CAST(dtime as DATE), n.l_id
order by n.l_id;
在旧版本的Postgres中,您可以使用条件聚合来实现此目标:
avg(case when n.day_number = 6 and n.fromorto = 'T' then mean_speed end) as ms_sat_t,