sql - Finding top 3 IDs with the largest count, by group - is it possible to avoid a triple nested query? -
i need find top 3 'userids' 'time' in terms of count in 'table'. example of input , output:
table
id userid time 1 '1' 2 '1' 3 b '2' 4 b '4' 5 b '4' etc
desired result:
time userid number rank '1' 17 1 '1' c 11 2 '1' q 9 3 '2' b 13 1 '2' c 9 2 '2' m 7 3 etc
i've been able accomplish using triple query there way simplify?
select userid, number, time, rank ( select userid, number, time, rank() on (partition time order number desc) rank (select count(distinct(id)) number, userid, time table group 2, 3) ) rank <= 3
i'm wondering if 'having' clause applicable here, since seems slow otherwise.
are happy this?
;with cte_ranking ( select time, userid, count(time) number, rank() on (partition time order count(time) desc) rank table group time,userid ) select * cte_ranking rank < 3 order time
Comments
Post a Comment