I have a query that returns the following result set:
patName SName DISC SCHEDULE
JM AA HA 2 per Week
JM MAC MSW 1 per Month
JM ANG RN 1 per Week
JM JON RN 1 per Week
JM LRH RN 1 per Week
Is there any way I could display the result as follows using PIVOT
PATNAME HA MSW RN
JM AA 2/Week MAC 1/Month ANG 1/week
JON 1/Week
LRH 1/Week
Edit, my query is as follows:
SELECT PatientName, [RN], [HA], [LVN], [MSW], [SC]
FROM
(
SELECT DISTINCT (tblPatient.FirstName +' '+ tblPatient.LastName) As PatientName,
(tblStaff.StaffFirstName+' '+tblStaff.StaffLastName) As StaffName,
(tblStaffDiscipline.Discipline)As Discipline,
CAST(tblFrequencyOfVisit.NoOfVisit As Varchar)+' per '
+ REPLACE (tblFrequencyOfVisit.Period,'/','') AS Visits new_value,
row_number() over(partition by PatientName, Discipline order by Discipline) rowNum
FROM tblPatient INNER JOIN
tblFrequencyOfVisit
ON tblPatient.PatientId = tblFrequencyOfVisit.PatientId
INNER JOIN tblStaffAssignment
ON tblPatient.PatientId = tblStaffAssignment.PatientId
AND tblFrequencyOfVisit.PatientId = tblStaffAssignment.PatientId
INNER JOIN tblStaffDiscipline
ON tblFrequencyOfVisit.DisciplineId = tblStaffDiscipline.DisciplineId
INNER JOIN tblStaff
ON tblStaffAssignment.StaffId = tblStaff.StaffId
AND tblStaffDiscipline.Discipline = tblStaff.StaffDisciplane
)src
pivot
(
max(new_value)
for Discipline in ([RN], [HA], [LVN], [MSW], [SC])
) piv
WHERE
tblpatient.PatientId = '138'
AND NOT tblPatient.SOC IS NULL
AND tblPatient.EOC IS NULL
AND tblPatient.Hospiceid = '1'
AND tblFrequencyofVisit.FromDate =
(Select MAX(FROMDATE)
From tblfrequencyofVisit
Where tblFrequencyOfVisit.PatientId = tblPatient.PatientId
AND tblFrequencyofVisit.Disciplineid = tblStaffDiscipline.Disciplineid )
You can use the
PIVOTfunction to perform this. If you have known values, then you can hard-code the columns using a static pivot. To get the grouping correct in thePIVOT, I included arow_number()so the result will include each record not just themax()value perpatname:See SQL Fiddle with Demo
If you have unknown values in the
DISCfield, then you can use dynamic SQL to pivot the data:See SQL Fiddle with Demo
If you do not have a
PIVOTfunction available, then this can be replicated using an aggregate function and aCASEstatement:See SQL Fiddle with Demo
Edit, based on your query that you posted it looks like you might need to use something like this: