15 Days of Learning SQL — HackerRank Advanced SQL Joins

Amber Ivanna Trujillo
3 min readOct 21, 2020

Julia conducted a days of learning SQL contest. The start date of the contest was March 01, 2016 and the end date was March 15, 2016.

Write a query to print total number of unique hackers who made at least submission each day (starting on the first day of the contest), and find the hacker_id and name of the hacker who made maximum number of submissions each day. If more than one such hacker has a maximum number of submissions, print the lowest hacker_id. The query should print this information for each day of the contest, sorted by the date.

Input Format

The following tables hold contest data:

  • Hackers: The hacker_id is the id of the hacker, and name is the name of the hacker.
  • Submissions: The submission_date is the date of the submission, submission_id is the id of the submission, hacker_id is the id of the hacker who made the submission, and score is the score of the submission.

Sample Input

For the following sample input, assume that the end date of the contest was March 06, 2016.

Hackers Table:

Submissions Table:

Sample Output

2016-03-01 4 20703 Angela
2016-03-02 2 79722 Michael
2016-03-03 2 20703 Angela
2016-03-04 2 20703 Angela
2016-03-05 1 36396 Frank
2016-03-06 1 20703 Angela

Explanation

Solution

SELECT sd, 
cnt,
h.hacker_id,
h.name
FROM (SELECT sd,
(SELECT Count(DISTINCT h.hacker_id)
FROM hackers h
JOIN submissions s
ON s.hacker_id = h.hacker_id
WHERE s.submission_date <= sd
AND (SELECT Count(DISTINCT submission_date)
FROM hackers hh
JOIN submissions ss
ON ss.hacker_id = hh.hacker_id
WHERE hh.hacker_id = h.hacker_id
AND ss.submission_date <= sd) =
1 + Datediff(sd, '2016-03-01')) AS cnt,
(SELECT h.hacker_id
FROM hackers h
JOIN submissions s
ON s.hacker_id = h.hacker_id
WHERE s.submission_date = sd
GROUP BY h.hacker_id
ORDER BY Count(s.submission_id) DESC,
h.hacker_id
LIMIT 1) AS hacker_id,
(SELECT Count(s.submission_id)
FROM hackers h
JOIN submissions s
ON s.hacker_id = h.hacker_id
WHERE s.submission_date = sd
GROUP BY h.hacker_id
ORDER BY Count(s.submission_id) DESC,
h.hacker_id
LIMIT 1) AS hacker_cnt
FROM (SELECT submission_date sd
FROM submissions
GROUP BY submission_date) AS date_tbl) AS TBL2
JOIN hackers h
ON h.hacker_id = TBL2.hacker_id
ORDER BY sd

Expected output

2016-03-01 112 81314 Denise 
2016-03-02 59 39091 Ruby
2016-03-03 51 18105 Roy
2016-03-04 49 533 Patrick
2016-03-05 49 7891 Stephanie
2016-03-06 49 84307 Evelyn
2016-03-07 35 80682 Deborah
2016-03-08 35 10985 Timothy
2016-03-09 35 31221 Susan
2016-03-10 35 43192 Bobby
2016-03-11 35 3178 Melissa
2016-03-12 35 54967 Kenneth
2016-03-13 35 30061 Julia
2016-03-14 35 32353 Rose
2016-03-15 35 27789 Helen

--

--

Amber Ivanna Trujillo

I am Executive Data Science Manager. Interested in Deep Learning, LLM, Startup, AI-Influencer, Technical stuff, Interviews and much more!!!