簡體   English   中英

select 每組的平均值在一列中具有相同值,在另一列中具有最大值

[英]select avg from each group that has same value in one column and max in other

我一直在努力尋找答案,但似乎沒有人遇到與我類似的問題,所以我決定在這里發布。
我有一個包含 200 條記錄的表,在fix_id列中具有重復值,在列時間戳中,每條記錄的值都在 1 到 5 之間,在最后一列中我得到了年齡值。
我喜歡 select 對於在fix_id列中具有相同 id 的每個組,同時在時間戳列中保持最大值,年齡列的平均值,並且有一個棘手的位,即年齡列有時可以具有值 0,在此情況下,我喜歡跳過這個值。

 fix_id   timestamp  age
  10         2        0
  10         2        2
  10         4        0
  10         4        1
  10         4        3
  5          4        2
  5          4        4
  5          3       10

所以從這張表中,我想得到這個結果

 fix_id    timestamp   age
  10          4         2
  5           4         3

因此,如果年齡列中有 0,我不想在計算平均值時包含它。
這可能嗎?

一種方法是帶有過濾的聚合查詢:

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;

如果您在查詢中設置條件,例如:

WHERE age > 0

那么您將錯過最大時間戳在列age中僅包含0 s 並且您不會在結果中獲得該fix_id的情況。
所以使用條件聚合:

SELECT t.fix_id, t.timestamp, 
       AVG(CASE WHEN t.age > 0 THEN t.age END) average_age
FROM tablename t
WHERE t.timestamp = (SELECT MAX(timestamp) FROM tablename WHERE fix_id = t.fix_id)
GROUP BY t.fix_id, t.timestamp

演示
結果:

| fix_id | timestamp | average_age |
| ------ | --------- | ----------- |
| 5      | 4         | 3           |
| 10     | 4         | 2           |

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM