【问题标题】:groupBy Clause Postgres按条款 Postgres 分组
【发布时间】:2019-03-26 01:36:31
【问题描述】:
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)。我不确定是否要编写子查询。任何帮助,将不胜感激。

【问题讨论】:

  • 帮助我们帮助您 - 请分享一些示例数据以及您希望获得的结果。
  • 结果列 - l_id、ms_saturday_from、ms_saturday_to、ms_sunday_from、ms_sunday_to。 ms 代表平均速度。 dtime 是一个时间戳(数据按小时分组)。我的结果必须按天分组。

标签: sql postgresql group-by


【解决方案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,

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多