7

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 ...

4
  • What do you mean with "first result"? There is only one maximum hittime per partition. Commented Nov 23, 2013 at 12:50
  • this window query will return me the whole table, when I am only interested in the max result. Distinct, as suggested by @amirreza-keshavarz helps in this case. Commented Nov 23, 2013 at 17:12
  • What i can't see why you don't want to use the GROUP BY. And both your second query and Amirezza's have a redundant order by hittime desc Commented Nov 23, 2013 at 17:15
  • My question may not have been specific enough. The GROUP BY works without problems, but what to do when I want eg. max and the second largest? Commented Nov 23, 2013 at 21:15

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

Comments

2

Use distinct statement.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.