Postgres SQL:如何为postgres中的相同时间戳选择“媒体”列中的最大值?

问题描述 投票:1回答:1

我正在通过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 
sql postgresql group-by max greatest-n-per-group
1个回答
1
投票

在Postgres中,只需使用distinct on即可解决每组前1个问题:

select distinct on (timestamp) ma.*
from monitoring_aggregate ma
order by timestamp, media desc
© www.soinside.com 2019 - 2024. All rights reserved.