Sample Header Ad - 728x90

Total days on consecutive date records up to gap

0 votes
1 answer
123 views
I have a classic Gaps and Islands issue whereby I need to total the time across the most recent records as far back as the first gap in dates Looking at , this provides a very neat solution to my question except that it does not work for sql server, there are syntax errors. Does anyone have an equivalent solution that works for sql server? The data is something like this | REF |TNCY-START| TNCY-END | |:----: |:--------:|:--------:| | 1 |2022-08-22| 2024-04-22| | 1 |2019-04-29| 2022-08-21| | 1 |2017-06-26| 2019-04-28| | 1 |2009-06-29| 2010-01-31| | 2 |2020-07-13| NULL | | 2 |2020-05-18| 2020-07-12| | 2 |2020-01-13| 2020-05-17| | 2 |2010-12-06| 2016-08-28| | 2 |2003-09-29| 2009-06-01| | 3 |2019-03-25| NULL | | 4 |2022-08-22| NULL | | 4 |2019-04-29| 2022-08-21| | 4 |2017-06-26| 2019-04-28| | 4 |2009-06-29| 2010-01-31|
create table #test ([PERSON-REF] INT, 
                   [TNCY-START] DATE,
                   [TNCY-END] DATE);
INSERT INTO #test VALUES


('1', '2022-08-22 00:00:00.000',	'2024-04-22 00:00:00.000'),
('1',	'2019-04-29 00:00:00.000',	'2022-08-21 00:00:00.000'),	
('1',	'2017-06-26 00:00:00.000',	'2019-04-28 00:00:00.000'),	
('1',	'2009-06-29 00:00:00.000',	'2010-01-31 00:00:00.000'),
('2',	'2020-07-13 00:00:00.000',	null),
('2',	'2020-05-18 00:00:00.000',	'2020-07-12 00:00:00.000'),
('2',	'2020-01-13 00:00:00.000',	'2020-05-17 00:00:00.000'),
('2',	'2010-12-06 00:00:00.000',	'2016-08-28 00:00:00.000'),
('2',	'2003-09-29 00:00:00.000',	'2009-06-01 00:00:00.000'),
('3',	'2019-03-25 00:00:00.000',	NULL),
('4',	'2022-08-22 00:00:00.000',	NULL),
('4',	'2019-04-29 00:00:00.000',	'2022-08-21 00:00:00.000'),
('4',	'2017-06-26 00:00:00.000',	'2019-04-28 00:00:00.000'),
('4',	'2009-06-29 00:00:00.000',	'2010-01-31 00:00:00.000')

SELECT * FROM #test;
and I want to end up with a single row per person ref containing person-ref, count of records after gap, start date after gap, latest end date (or null), days between. eg assuming UK date format and taking null as today | REF |COUNT OF TENANCIES |FIRST TNCY-START|LAST TNCY-END|TOTAL TENANCY DAYS| |:----:|:----------------:|:--------------:|:------------:|:----------------:| | 1 | 3 |2017-06-26 | 2024-04-22 |2492| | 2 | 3|2020-01-13|NULL|1562| |3|1|2019-03-25|NULL|1866| |4|3|2017-06-26|NULL|2493| Thanks for any help anyone can offer
Asked by Judy D (3 rep)
Apr 23, 2024, 02:33 PM
Last activity: Apr 24, 2024, 10:35 AM