CREATE PROC [dbo].[sp_GetSubjectivesBySurfaceItemId]
	@surfaceItemId INT
AS

DECLARE @cols AS NVARCHAR(MAX),
		@query  AS NVARCHAR(MAX)

SELECT	@cols = STUFF((SELECT ',' + QUOTENAME(complaint) 
FROM	pal_vMedicalPatientSubjectiveDetails 
WHERE	surfaceItemId = @surfaceItemId
group by complaint, surfaceItemId
order by complaint
    FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
,1,1,'')
	
IF(@cols IS NULL)
BEGIN
	SELECT ''
END
ELSE
BEGIN	
set @query = N'SELECT
			*
			FROM
			(
				SELECT	date	Date
						,score	Score
						,complaint Complaint		
				FROM	pal_vMedicalPatientSubjectiveDetails 
				WHERE	surfaceItemId = '+CAST(@surfaceItemId AS VARCHAR)+'				
				) DataTable
			PIVOT
			(
				MAX(score)
				FOR complaint
				IN 
					(
						' + @cols + '
					)
			) PivotTable
			ORDER BY date
			'

exec sp_executesql @query;
END
--sp_GetSubjectivesBySurfaceItemId 5124

