【问题标题】:selecting average value from group of same with max on another for several columns从一组相同的组中选择平均值,在另一组中为几列选择最大值
【发布时间】:2020-09-08 14:38:36
【问题描述】:

我正在努力为另一列上具有最大值的一组相同 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;

这完全符合预期,但是,我需要为几列选择相同的方式平均值,我想知道是否有一种方法可以在一个查询中执行此操作。我可以的

平均(年龄),平均(身高)

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

【问题讨论】:

    标签: php mysql sql join select


    【解决方案1】:

    使用条件聚合:

    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;
    

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      相关资源
      最近更新 更多