首页 > 解决方案 > Postgres SQL:如何在postgres中为同一时间戳选择“媒体”列中的最大值?

问题描述

我通过 DataGrip 程序使用 possql。我有下表:

    timestamp       | Channel |  media
-----------------------------------------
2020-04-29 00:00:00 |   3     |   1.2
2020-04-29 00:00:00 |   4     |    2
2020-04-29 00:00:00 |   5     |    1
2020-04-29 00:10:00 |   3     |    2
2020-04-29 00:10:00 |   4     |   1.5
2020-04-29 00:10:00 |   5     |    3

我想按每个“时间戳”的“媒体”列中的最大值排序,如下所示:

    timestamp       | Channel |  media
-----------------------------------------
2020-04-29 00:00:00 |   4     |    2
2020-04-29 00:10:00 |   5     |    3

我怎样才能做到这一点?

我试图这样做,但它没有用,它重复原始表:

SELECT timestamp, max(media), channel
FROM monitoring_aggregate
GROUP BY timestamp, channel
ORDER BY timestamp 

标签: sqlpostgresqlgroup-bymaxgreatest-n-per-group

解决方案


在 Postgres 中,只是可以distinct on用来解决这个 top-1-per-group 问题:

select distinct on (timestamp) ma.*
from monitoring_aggregate ma
order by timestamp, media desc

推荐阅读