Skip to content

Instantly share code, notes, and snippets.

@khuyentran1401
Last active March 19, 2023 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khuyentran1401/ffe0490f47bf901fbe0a419fe05befae to your computer and use it in GitHub Desktop.
Save khuyentran1401/ffe0490f47bf901fbe0a419fe05befae to your computer and use it in GitHub Desktop.
Hackerrank SQL Challenges
/*
Julia asked her students to create some coding challenges. Write a query to print the hacker_id, name, and the total number of challenges created by each student. Sort your results by the total number of challenges in descending order. If more than one student created the same number of challenges, then sort the result by hacker_id. If more than one student created the same number of challenges and the count is less than the maximum number of challenges created, then exclude those students from the result.
*/
with count_table as (
select
h.hacker_id,
h.name,
count(*) challenge_count
from
challenges c
join hackers h on c.hacker_id = h.hacker_id
group by
h.hacker_id,
h.name
)
select
hacker_id,
name,
challenge_count
from
count_table
where
challenge_count in (
select
challenge_count
from
count_table
group by
challenge_count
having
count(challenge_count) <= 1
)
or challenge_count = (
select
max(challenge_count)
from
count_table
)
order by
challenge_count desc,
hacker_id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment