Expanding on from what I learned from @John-Cappelletti answer I had a fiddle around and came up with this solution that combines an XML Path query to help build a dynamic-sql query. This works for an unknown number of ColumnName values.
Posting it here as it may be of use to others
CREATE TABLE #TempTable(RowId int, ColumnName VARCHAR(20), DataValue VARCHAR(20)) INSERT INTO #TempTable VALUES (0, 'First Name', 'David'), (1, 'First Name', 'Sarah'), (0, 'Last Name', 'Jones'), (1, 'Last Name', 'Vaughan'), (0, 'Age', '100'), (1, 'Age', '50') -- Get the column names in the format [Name 1], [Name 2] -- as required for the Pivot query DECLARE @ColumnNames VARCHAR(MAX) = ( SELECT DISTINCT '[' + ColumnName + ']' + ',' AS 'data()' FROM #TempTable FOR XML path('') ) --- Remove the trailing comma (must be a better way to do this) SET @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames) - 1) --- Build the Pivot query DECLARE @SqlQuery VARCHAR(MAX) = 'Select * From #TempTable Pivot ( max(DataValue) for ColumnName in (' + @ColumnNames + ') ) pvt' EXEC(@SqlQuery)
MAXandMINare aggregates, and works on text also