Data Expose

0

Please login or register to vote for this query.

(click on this box to dismiss)

Emacs

Q&A for those using, extending or developing Emacs

CREATE table #yourtable
    ([Id] int, [Value] varchar(10), [ColumnName] varchar(13),[RowId] varchar(13))
;
    
INSERT INTO #yourtable
    ([Id], [Value], [ColumnName],[RowId])
VALUES
    (1, 'John', 'FirstName','E01'),
    (2, '2.4', 'Amount','E01'),
    (3, 'ZH1E4A', 'PostalCode','E01'),
    (4, 'Fork', 'LastName','E01'),
    (5, '857685', 'AccountNumber','E01'),
    (6, 'E01', 'RowId','E01'),
      (7, 'John1', 'FirstName','E011'),
    (8, '2.41', 'Amount','E011'),
    (9, 'ZH1E4A1', 'PostalCode','E011'),
    (10, 'Fork1', 'LastName','E011'),
    (11, '8576851', 'AccountNumber','E011'),
    (12, 'E011', 'RowId','E011')
  
;


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

select @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(ColumnName) 
                    from #yourtable
                    group by ColumnName, RowId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from #yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

Enter Parameters

Options:
Switch to meta site
loading Hold tight while we fetch your results