15 Days of Learning SQL

  • + 0 comments

    ms sql server with recursive, rank and row number:
    with cte as (select *, dense_rank() over(order by submission_date) as rank from submissions), cte1 as ( select distinct submission_date, submission_id, hacker_id, rank from cte where rank = 1 union all select cte.submission_date, cte.submission_id, cte.hacker_id, cte.rank from cte1 join cte on cte.hacker_id = cte1.hacker_id and cte.rank = cte1.rank + 1 ), cte3 as (select submission_date, hacker_id from (select submission_date, hacker_id, c ,row_number() over(partition by submission_date order by submission_date, c desc, hacker_id) r from ( select submission_date, hacker_id, count(hacker_id) c from submissions group by submission_date, hacker_id) n) c where r = 1)

    select n.submission_date, n.hacker, cte3.hacker_id, h.name from (select submission_date, count(distinct cte1.hacker_id) as hacker from cte1 group by submission_date) n join cte3 on n.submission_date = cte3.submission_date join hackers h on cte3.hacker_id = h.hacker_id