繁体   English   中英

为几列从一组相同的组中选择平均值,另一组为最大值

[英]selecting average value from group of same with max on another for several columns

我一直在努力 select 一组相同的 fix_ids 值的平均值,在另一列上具有最大值,最终有人帮助了我,我最终得到了这段代码

select fix_id
     , timestamp
     , avg(age)
  from t
 where age > 0 
   and timestamp = 
  (select max(t2.timestamp) 
    from t t2 
   where t2.fix_id = t.fix_id)
group by fix_id;

这正是它应该做的,但是,我需要 select 以相同的方式为几列平均值,我想知道是否有办法在一个查询中做到这一点。 我可以

avg(age),avg(height)

但是由于我跳过了年龄列高度值为 0 的行,因此将丢失这些行。

使用条件聚合:

select fix_id, timestamp,
       avg(case when age > 0 then age end) as avg_age,
       avg(height) as avg_height
from t
where timestamp = (select max(t2.timestamp) from t t2 where t2.fix_id = t.fix_id)
group by fix_id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM