Link to home
Start Free TrialLog in
Avatar of Jeff S
Jeff SFlag for United States of America

asked on

Dynamic SQL help

I need help rolling the results to one line for each unique patient per Assessment Date. The example is a test patient, no worries about a real patients data.

User generated image
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX);
DECLARE @ColumnName AS NVARCHAR(MAX);
 
--Get distinct values of the PIVOT Column 
SELECT
	@ColumnName = ISNULL(@ColumnName + ',' , '') + QUOTENAME(FieldName)
	FROM (SELECT DISTINCT FieldName FROM CusDARMHA_ImportExport) AS Courses;

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = N'SELECT DISTINCT
         PatientName 
        , PatientId 
        , InternalID 
        , ProfessionalID 
        , AssessmentDate 
        , AssessmentReasonCode 
        , InternalEpisodeCode 
        , InternalAssessmentID 
        , RecordIdentifier  
        , '+@ColumnName+'
    FROM CusDARMHA_ImportExport
   
    PIVOT(MAX(AnswerID) 
          FOR FieldName IN ('+@ColumnName+')) AS PVTTable
     
          
          GROUP BY 
          PatientName 
        , PatientId 
        , InternalID 
        , ProfessionalID 
        , AssessmentDate 
        , AssessmentReasonCode 
        , InternalEpisodeCode 
        , InternalAssessmentID 
        , RecordIdentifier
        ,'+@ColumnName+' ';
--Execute the Dynamic Pivot Query

EXEC sp_executesql
	@DynamicPivotQuery;

Open in new window

Avatar of ste5an
ste5an
Flag of Germany image

Remove the DISTINCT and the GROUP BY. The PIVOT clause is doing the "roll up" already.
Avatar of Jeff S

ASKER

I am still getting the same results and need to roll them up to one line.
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jeff S

ASKER

Thanks