-
Notifications
You must be signed in to change notification settings - Fork 218
/
Challenges.sql
28 lines (27 loc) · 897 Bytes
/
Challenges.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-- Use HAVING instead of WHERE since we have to filter on groups
-- Split the total number of counts into 2 pieces
-- First piece will be the largest number
-- Second piece will be the number which doesn't repeat (Unique) or is available once
select H.hacker_id, H.name, count(C.challenge_id) as total_count
from Hackers H join Challenges C
on H.hacker_id = C.hacker_id
group by H.hacker_id, H.name
having total_count =
(
select count(temp1.challenge_id) as max_count
from challenges temp1
group by temp1.hacker_id
order by max_count desc
limit 1
)
or total_count in
(
select distinct other_counts from (
select H2.hacker_id, H2.name, count(C2.challenge_id) as other_counts
from Hackers H2 join Challenges C2
on H2.hacker_id = C2.hacker_id
group by H2.hacker_id, H2.name
) temp2
group by other_counts
having count(other_counts) =1)
order by total_count desc, H.hacker_id