sql - 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
解决方案
在 Postgres 中,只是可以distinct on
用来解决这个 top-1-per-group 问题:
select distinct on (timestamp) ma.*
from monitoring_aggregate ma
order by timestamp, media desc
推荐阅读
- bash - Bash:用翻译替换特定文本
- ionic-framework - 我需要在 ionic 项目中添加多少个启动画面?
- typescript - Typescript 中的泛型导致意外错误
- sql - 关于informatica电力中心改造任务的问题
- scala - 从列表中的字符串替换/删除某些字符
- imagemagick - ImageMagick Linux 模仿 ezgif.com 结果
- xaml - xamarin 表单 - 列表视图 - 选择器 - 不会与列表视图中的行对齐
- mysql-8.0 - 是否可以将 mysql 从 8.0.24 回滚到 8.0.23?
- java - 使用 Java Streams 将字符串拆分为 Map
- python - 为什么当我尝试使用 virtualenv 时它不起作用?