You are viewing a single comment's thread. Return to all comments →
WITH cte0 AS( --Join of tables (Creating Master Table). SELECT s.submission_date, s.submission_id, s.hacker_id, h.name FROM submissions s LEFT JOIN hackers h ON s.hacker_id = h.hacker_id WHERE s.submission_date BETWEEN '2016-03-01' AND '2016-03-15'), cte1 AS( --Date & Sequence SELECT submission_date, ROW_NUMBER() OVER(ORDER BY submission_date ASC) AS dt_seq FROM cte0 GROUP BY submission_date), cte2 AS( --All hackers with at least one submission. SELECT hacker_id, submission_date, COUNT(submission_id) AS sb_count FROM cte0 GROUP BY hacker_id, submission_date HAVING COUNT(submission_id)>0), cte3 AS( --All hackers with at least one submission each day. SELECT hacker_id, submission_date, ROW_NUMBER() OVER(PARTITION BY hacker_id ORDER BY submission_date) AS h_seq FROM cte2), cte4 AS ( -- result of first query SELECT cte3.submission_date, COUNT(hacker_id) AS num_hackers FROM cte3 JOIN cte1 ON cte1.submission_date = cte3.submission_date AND cte1.dt_seq = cte3.h_seq GROUP BY cte3.submission_date), cte5 AS ( SELECT submission_date, hacker_id, RANK() OVER(PARTITION BY submission_date ORDER BY sb_count DESC, hacker_id ASC) AS rnk FROM cte2), cte6 AS ( -- result of 2nd query SELECT submission_date, hacker_id FROM cte5 WHERE rnk=1), cte7 AS ( SELECT hacker_id, name FROM cte0 GROUP BY hacker_id, name) SELECT cte4.submission_date, cte4.num_hackers, cte6.hacker_id, cte7.name FROM cte4 JOIN cte6 ON cte6.submission_date = cte4.submission_date JOIN cte7 ON cte7.hacker_id = cte6.hacker_id ORDER BY cte4.submission_date;
Seems like cookies are disabled on this browser, please enable them to open this website
15 Days of Learning SQL
You are viewing a single comment's thread. Return to all comments →