Question

I have a set of data that appears as below:

PatientID   Custodian
17          Parent1
17          Parent2
18          Parent1
18          Parent2
18          Parent3
19          Parent1

I want output as:

PatientID    Custodian 1         Custodian 2         Custodian 3
17           Parent1             Parent2
18           Parent1             Parent2             Parent3
19           Parent1

Please help in writing SQL query for this.

Was it helpful?

Solution

You could use the PIVOT function, but you'd need to add a column with the matching Custodian ID. You COULD use some dynamic SQL for the 'custodian IN' section, but it could get messy. Something like this on the PIVOT:

CREATE TABLE #Temp
(
PatientID INT NOT NULL
,Custodian VARCHAR(10) NOT NULL
)

INSERT INTO #Temp
VALUES
(17,'Parent1')
,(17,'Parent2')
,(18,'Parent1')
,(18,'Parent2')
,(18,'Parent3')
,(19,'Parent1')

CREATE TABLE #Temp2
    (
    PatientID INT NOT NULL
    ,Parent VARCHAR(20) NOT NULL
    ,Custodian VARCHAR(20) NOT NULL
    )

INSERT INTO #Temp2
SELECT
    a.PatientID
    ,a.Custodian Parent
    ,'Custodian' + SUBSTRING(Custodian,7,10) Custodian
FROM #Temp a

SELECT *
FROM #Temp2 a (NOLOCK)
PIVOT (
    MAX(Parent)
    FOR Custodian IN ([Custodian1],[Custodian2],[Custodian3]))
    AS ParentID

DROP TABLE #Temp
DROP TABLE #Temp2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top