merge contiguous rows with same flag

  • Hi,

    I have a table with two columns [month] and [flag]. Sample Data is given below.

    [month] [flag]

    20070101 1

    20070201 1

    20070301 2

    20070401 2

    20070501 NULL

    20070601 1

    20070701 1

    20070801 1

    The month field is always contiguous (no missing months). Flag can be any number. I need to merge these rows into spans.

    needed output:

    start end flag

    20070101 20070301 1

    20070301 20070501 2

    20070501 20070601 NULL

    20070601 20070801 1

    I can use while loop or cursor to accomplish this but I was wondering if there is a set based approach to solve this problem?

    Appreciate your help.

  • i figured it out.. simple update will work

    declare @timeline table(

    [month] varchar(8),

    [enddate] varchar(8),

    flag char(1)

    )

    update t1 set enddate = (select min([month]) from @timeline where flag<>t1.flag and [month]>t1.[month]) from @timeline t1

    select min([month]), enddate, flag from @timeline group by enddate, flag

  • Cool. Thanks for posting the solution!

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Well, here's my solution[/url], not really specific to SQL server, just generic SQL

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply