Tuesday, May 22, 2018

Show Rows as Columns in SQL Server

SELECT TOP 1000 [ID]
      ,[Name]
      ,[Salary]
      ,[Department]
      ,[Sex]
      ,[UserId]
      ,[ManagerID]
  FROM [TestDatabase].[dbo].[Employees]


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

select @cols = STUFF((SELECT ',' + QUOTENAME(Name)
                    from Employees
                    group by Name, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from
             (
                select ID, Name
                from Employees
            ) x
            pivot
            (
                max(ID)
                for Name in (' + @cols + N')
            ) p '

exec sp_executesql @query;



for Department

set @query = N'SELECT ' + @cols + N' from
             (
                select Name, Department
                from Employees
            ) x
            pivot
            (
                max(Department)
                for Name in (' + @cols + N')
            ) p '

No comments:

Post a Comment