Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Fill gap in date periods

Author  Topic 

Clas
Starting Member

33 Posts

Posted - 2012-08-25 : 05:27:59

Create and fill gap in dateperiod

create table #source
(
individual int,
movingIN date,
movingOut date,
household int
)



Insert INTO #source
SELECT '3','1858-06-27', '1873-10-31','100'
UNION ALL SELECT '3','1877-11-01', '1884-09-05','100'
UNION ALL SELECT '4','1861-04-26', '1875-10-31','100'
UNION ALL SELECT '4','1875-10-31', '1881-11-09','300'
UNION ALL SELECT '4','1881-11-09', '1882-07-01','100'
UNION ALL SELECT '4','1882-11-02', '1883-11-22','400'
UNION ALL SELECT '4','1884-11-22', '1885-05-20','100'



Gap (household -1):

3 1873-10-31 1877-11-01 -1
4 1882-07-01 1882-11-02 -1
4 1883-11-22 1884-11-22 -1


RESULT:
individual movingIN movingOut household
3 1858-06-27 1873-10-31 100
3 1873-10-31 1877-11-01 -1
3 1877-11-01 1884-09-05 100
4 1861-04-26 1875-10-31 100
4 1875-10-31 1881-11-09 300
4 1881-11-09 1882-07-01 100
4 1882-07-01 1882-11-02 -1
4 1882-11-02 1883-11-22 400
4 1883-11-22 1884-11-22 -1
4 1884-11-22 1885-05-20 100


THANKS !

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-08-25 : 10:03:53
[code]; with cte as
(
select *, rn = row_number() over (partition by individual order by movingIN)
from #source
)
select c1.individual, movingIN = c1.movingOut, movingOut = c2.movingIN, household = -1
from cte c1
inner join cte c2 on c1.individual = c2.individual
and c1.rn = c2.rn - 1
where c1.movingOut <> c2.movingIN

union all

select individual, movingIN, movingOut, household
from cte[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -