Limit result set in sql window function

六眼飞鱼酱① 提交于 2019-12-12 14:27:57

问题


Assume I would like to rewrite the following aggregate query

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

using an aggregate windowing function like

select id, max(hittime) over(partition by id order by hittime desc) from status

How can I specify, that I am only interested in the first result within the partition?

EDIT: I was thinking that there might be a solution with [ RANGE | ROWS ] BETWEEN frame_start AND frame_end. What to get not only max(hittime) but also the second, third ...


回答1:


I think what you need is a ranking function, either ROW_NUMBER or DENSE_RANK depending on how you want to handle ties.

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



回答2:


Use distinct statement.

select DISTINCT id, max(hittime) over(partition by id order by hittime desc) from status


来源:https://stackoverflow.com/questions/20161109/limit-result-set-in-sql-window-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!