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
 Missing Data

Author  Topic 

andygill
Starting Member

3 Posts

Posted - 2012-09-25 : 06:59:36
Hi All

Can anyone help me with some code (I’ve been struggling with it all day !!)

I have this table (clusters)

NHS_No Cluster_No startdate enddate
1234 6 01/04/12
5678 9 01/05/12 31/05/12
1234 7 01/06/12 13/06/12

If the enddate is empty I need it to be the nearest startdate of those records with a matching NHS_No.

So in this case it would be 01/06/12

Thanks for your help

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-25 : 07:29:16
One way to approach it is by joining the table to itself 3 times. There may be simpler ways, but this is the only one that comes to my mind right now :)
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY NHS_No ORDER BY StartDate) AS RN
FROM YourTable
)
SELECT
a.NHS_No,
a.Cluster_no,
a.StartDate,
COALESCE(a.endDate,
CASE
WHEN DATEDIFF(dd,COALESCE(b.startDate,'19000101'),a.startDate) >
DATEDIFF(dd,a.startDate,COALESCE(c.startDate,'19000101')) THEN
b.startDate
ELSE c.startDate
END) AS EndDate
FROM
cte a
LEFT JOIN cte b ON b.RN+1 = a.RN
LEFT JOIN cte c ON c.RN-1 = a.RN
ORDER BY
a.NHS_No,
a.ClusterNo,
a.StartDate;
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2012-09-25 : 07:37:08
SET DATEFORMAT DMY

DECLARE @Table TABLE (NHS_NO int,Cluster_No int,StartDate date, EndDate date)

INSERT INTO @Table
VALUES
(1234, 6,'01/04/12',null) ,
(5678, 9,'01/05/12','31/05/12'),
(1234, 7,'01/06/12','13/06/12')


UPDATE t
SET EndDate = tt.StartDate
FROM @Table t

CROSS APPLY(select top 1 StartDate
from @Table t2
where t.NHS_NO = t2.NHS_NO and t2.StartDate > t.StartDate
order by StartDate
)tt

SELECT * FROM @table


Jim

Everyday I learn something that somebody else already knew
Go to Top of Page
   

- Advertisement -