sql server rows to columns code example

Example 1: sql server pivot rows to columns

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

Example 2: convert rows to columns in sql server

-- convert rows to columns in sql server (PIVOT)
SELECT Firstname, Amount, PostalCode
FROM (
         SELECT value, columnname
         FROM yourtable
     ) d
PIVOT (
    max(value)
    FOR columnname IN (Firstname, Amount, PostalCode)
) piv;

Example 3: sql server pivot rows to columns

-- Dynamic Pivot with unknown number of columnnames

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

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            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;

Tags:

Sql Example