March 6, 2008 at 4:59 pm
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.
March 6, 2008 at 5:26 pm
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
March 6, 2008 at 9:31 pm
Cool. Thanks for posting the solution!
--Jeff Moden
Change is inevitable... Change for the better is not.
January 18, 2012 at 2:24 pm
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply