I am trying to look at my database of administered table where we can see when a member has been administered and released from the rehab center. The sample table would look something like this:
SAMPLE TABLE:
ID. | MEMID | START | END |
---|---|---|---|
01 | 99988 | 01/01/2020 | 03/30/2020 |
02 | 99988 | 04/01/2020 | 12/31/2020 |
03 | 99988 | 01/01/2021 | 12/31/2021 |
04 | 99988 | 04/01/2022 | 12/31/2022 |
05 | 99989 | 01/01/2015 | 12/31/2020 |
06 | 99990 | 01/01/2017 | 09/31/2017 |
07 | 99990 | 08/01/2017 | 12/31/2018 |
08 | 99991 | 01/01/2013 | 012/31/2017 |
09 | 99992 | 01/01/2017 | 09/31/2019 |
10 | 99992 | 10/01/2019 | 12/31/2021 |
EXPECTED OUTPUT:
MEMID | START | END |
---|---|---|
99988 | 01/01/2020 | 12/31/2021 |
99990 | 01/01/2017 | 12/31/2018 |
99992 | 01/01/2017 | 12/31/2021 |
I am supposed to get the patients who had contiguous administration i.e. if they leave on join on 5th july of 2015, leave on 3rd of october and come back on 4th october and leave on 7th of december, I'd need to have that patient in the output with a single date range i.e 5th of july to 7th of december. My query:
SELECT id, mimed, start, end
FROM administered
UNION ALL
(
SELECT n.id, n.memid, n.start, n.end
FROM administered n JOIN result r on n.memid = r.memid
WHERE n.start = DATEADD(day, 1, r.end)
)
)
SELECT MIN(start) as start, MAX(end) as end, memid
FROM result
GROUP BY memid
OPTION(MAXRECURSION 0)
I'm pretty sure there's something that I am not understanding regarding how to set up a base case or even the termination condition on this one.