SQL Programmers Hive Mind Query

I've been asked to compile a list of subscribers grouped into subsets of 5, 10, 20, and 30 years of consecutive seasons, with the catch of "consecutive" meaning no more than a 2 year gap between seasons.  Can anyone take a crack at showing this intermediate (at best) SQL programmer how to do that using (I assume) some sort of WHILE loop logic?

What would be most helpful is even just a way to output, for each distinct(customer_no) in T_SUBSCRIPTION_HIST, the number of consecutive seasons as a separate row.  I realize that such a table would have some customers show up more than once, but then I figure I could simply use a SELECT customer_no, MAX(num_cons_seasons) for each constituent, right?

Thank you, Tessiturians.  I suspect I will get a lot of use out of this logic in future.

On this Day in History:  The first commercial jet (the British De Haviland Comet) takes its first test flight.

Parents Reply Children
  • Here's a little ditty I wrote to get consecutive years giving. Maybe something like this would work using t_cust_subscription_summary?

     

     

    declare @tot_years table(customer_no int, fyear int)
    insert into @tot_years
    select distinct customer_no, fyear from vs_contribution a
    join t_campaign b on a.campaign_no = b.campaign_no
    select a.customer_no, max(a.fyear) as 'Last_Fyear', min(b.fyear) as 'First_Fyear', max(a.fyear)-min(b.fyear) as'Tot_Consecutive_Years'
    from @tot_years a
    join @tot_years b on a.customer_no = b.customer_no
    where a.customer_no = 222315
    group by a.customer_no
    having max(a.fyear-1) in (select fyear from @tot_years where customer_no = a.customer_no)
    and max(a.fyear+1) not in(select fyear from @tot_years where customer_no = a.customer_no)
    and min(b.fyear-1) not in(select fyear from @tot_years where customer_no = a.customer_no)
    and min(b.fyear+1) in (select fyear from @tot_years where customer_no = a.customer_no)

     



    [edited by: Brian Graham at 6:00 PM (GMT -6) on 1 Aug 2011]