15 Days of Learning SQL

  • + 0 comments

    Good solution using recursion:

    with funnel as (
        select
            submission_date as cur,
            hacker_id
        from 
            submissions
        where 
            1=1
            and submission_date = (select min(submission_date) from submissions)
        
        union all 
        
        select
            dateadd(day, 1, f.cur) as cur,
            s.hacker_id
        from   
            funnel f
        join 
            submissions s 
            on s.hacker_id = f.hacker_id 
            and s.submission_date = dateadd(day, 1, f.cur)
    ),
    
    funnel_counting as (
        select
            cur as submission_date,
            count(distinct hacker_id) as hackers_funnel
        from 
            funnel
        group by cur
    ),
    
    submissions_hacking as (
        select
            submission_date,
            hacker_id,
            count(submission_id) as submissions
        from 
            submissions 
        group by submission_date, hacker_id
    ),
    
    submissions_rn as (
        select
            submission_date,
            hacker_id,
            row_number() over (partition by submission_date order by submissions desc, hacker_id asc) as rn 
        from    
            submissions_hacking
    )
    
    select
        fc.submission_date,
        fc.hackers_funnel,
        sr.hacker_id,
        h.name as hacker_name
    from 
        funnel_counting fc
    join 
        submissions_rn sr
        on fc.submission_date = sr.submission_date
    join 
        hackers h
        on sr.hacker_id = h.hacker_id
    where
        1=1
        and sr.rn = 1
    order by fc.submission_date
    option(maxrecursion 0);