sql - 限制sql窗口函数中的结果集

标签 sql aggregate-functions

假设我想重写以下聚合查询

select id, max(hittime)
from status
group by id

使用聚合窗口函数,如
select id, max(hittime) over(partition by id order by hittime desc) from status

如何指定我只对分区中的第一个结果感兴趣?

编辑:我在想 [ RANGE | ] 可能有一个解决方案ROWS ] 在 frame_start 和 frame_end 之间。不仅要获得 max(hittime) 还要获得第二、第三...

最佳答案

我认为您需要的是一个排名函数,ROW_NUMBER 或 DENSE_RANK 取决于您想要如何处理关系。

select id, hittime
from (
     select id, hittime,
            dense_rank() over(partition by id order by hittime desc) as ranking
     from status
     ) as x
where ranking = 1;  --to get max hittime
--where ranking <=2;  --max and second largest

关于sql - 限制sql窗口函数中的结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20161109/

相关文章:

sql - Postgres SQL 查询返回 JSON 对象,其中包含一列中的键和另一列中的值

sql - 创建外键而不检查现有数据

Python:如何知道我正在连接哪个数据库?

python - select 语句获取所有相同的记录,但只有一个字段不同

sql - 在时间间隔内选择第一行和最后一行

PostgreSQL:heroku 数据库服务器上的 array_agg() 内存不足问题

sql-server - SQL Server 中计算中位数的函数

java - 使用 JavaFX 将数据写入 MySQL 表

sql - 从默认 getdate() azure sql 中减去 6 小时

mysql - MySQL GROUP BY 的 PostgreSQL 等价物