15 Days of Learning SQL

  • + 0 comments
    --SQL
    
     
    SELECT z.submission_date,
           z.total_count,
           z.hacker_id,
           c.name
    FROM
      (SELECT y.*,
              sum(CASE
                      WHEN y.rn = y.sub_date_cnt THEN 1
                      ELSE 0
                  END) OVER (PARTITION BY submission_date) AS total_count,
              dense_rank() OVER (PARTITION BY submission_date
                                 ORDER BY cnt DESC, hacker_id) AS rnk
       FROM
         (SELECT a.hacker_id,
                 a.submission_date,
                 x.rn,
                 sum(CASE
                         WHEN a.submission_date = b.submission_date THEN 1
                         ELSE 0
                     END) AS cnt ,
                 count(DISTINCT b.submission_date) AS sub_date_cnt
          FROM
            (SELECT Submission_date,
                    rank() OVER (
                                 ORDER BY Submission_date) AS rn
             FROM
               (SELECT DISTINCT submission_date
                FROM Submissions
                WHERE submission_date >= '2016-03-01'
                  AND submission_date <= '2016-03-15'))x
          LEFT JOIN Submissions a ON a.Submission_date = x.Submission_date
          LEFT JOIN Submissions b ON a.hacker_id = b.hacker_id
          AND b.Submission_date <= a.submission_date
          GROUP BY a.hacker_id,
                   a.submission_date,
                   x.rn
          ORDER BY a.submission_date,
                   sum(CASE
                           WHEN a.submission_date = b.submission_date THEN 1
                           ELSE 0
                       END) DESC , a.hacker_id) y) z
    LEFT JOIN hackers c ON z.hacker_id = c.hacker_id
    WHERE z.rnk = 1
    ORDER BY submission_date ;