A hospital database (SQL Server 2016) has a table of visits to the hospital. If patients transfer to a different specialty, a new visit is made (but from a research perspective it's considered one admission overall).
I've got the below CTE to join connected visits (gaps and islands problem) to form admissions (based on the admit/discharge time of the visit).
WITH cte1 AS ( SELECT v.*, PrevEnd = LAG(v.DischargeDate) OVER (PARTITION BY v.PatientID ORDER BY v.AdmitDate) FROM Visits v),cte2 AS ( SELECT *, GroupId = COUNT(CASE WHEN cte1.PrevEnd >= DATEADD(hour, -6, cte1.AdmitDate) THEN NULL ELSE 1 END) OVER (PARTITION BY cte1.PatientID ORDER BY cte1.AdmitDate ROWS UNBOUNDED PRECEDING) FROM cte1),Numbered AS ( SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY cte2.PatientID, cte2.GroupID ORDER BY cte2.AdmitDate) FROM cte2)
The issue is I would like to create a dataset from this CTE, where there's a dynamic number of VisitID[n]
columns based on the MAX(rn) FROM Numbered
, instead of specifying each VisitID[n]
column manually as I've done below:
SELECT n.PatientID, AdmitDate = MIN(n.AdmitDate), DischargeDate = MIN(n.DischargeDate), VisitID = MIN(CASE WHEN n.rn = 1 THEN n.VisitID END), VisitID2 = MIN(CASE WHEN n.rn = 2 THEN n.VisitID END), VisitID3 = MIN(CASE WHEN n.rn = 3 THEN n.VisitID END), VisitID4 = MIN(CASE WHEN n.rn = 4 THEN n.VisitID END)FROM Numbered nGROUP BY n.PatientID, n.GroupIDORDER BY n.PatientID, n.GroupID;
Image may be NSFW.
Clik here to view.
The actual Numbered
CTE result may have at least 20 connected visits.
I attempted to create a dynamic SQL string I could use exec
on, by putting the CTE into a Temp table, but I was met with Error converting data type varchar to bigint
.
DECLARE @maxVisitIDCount INT;DECLARE @columnNames NVARCHAR(MAX) = '';SELECT * INTO #tempVisitGrouped FROM NumberedSELECT @maxVisitIDCount = MAX(rn) FROM #tempVisitGrouped;SELECT @columnNames = @columnNames +'[VisitID'+ a.rn +'],' FROM (SELECT TOP (@maxVisitIDCount - 1) * FROM #tempVisitGrouped) AS a;
I thought I'd ask dba incase there's an easier way to do what I want. How can I generate the number of VisitID
columns dynamically?