Home > OS >  Pivot employee table in SQL Server?
Pivot employee table in SQL Server?

Time:01-28

I have written the query to get the first result in SQL Server.

And I want to pivot this table into the following format. I need help pivoting this table in SQL Server.

Pivoting in SQL Server

CodePudding user response:

If you want to Pivot a table in sql server here is how you do it

select [Division],[December],[January],[February]
from(
    select * from SOF
) tbl
pivot(
    Min(Emp) for Month in ([December],[January],[February])
) pvt

This query will get your results according to provided data. This is how PIVOT works.

select 
   <non pivot column 1>,
   <non pivot column 2>,
   <pivoted column 1>,
   <pivoted column 2>,
    ............
from (
   --Result from the query
   select * from yourTable
) tbl
pivot(
   <Aggregation function> For [<column that contains the values that will become column headers>]
   IN ( [first pivoted column], [second pivoted column],  
... [last pivoted column])  
)

CodePudding user response:

You can go for simple PIVOT as given below:

DECLARE @table table(division varchar(30), emp int, month varchar(30))

INSERT INTO @table
values
('AAA',50,'December')
,('BBB',100,'December')
,('AAA',200,'January')
,('BBB',150,'January')
,('AAA',60,'February')
,('BBB',70,'February ')


SELECT * FROM @table
pivot (sum(emp) for month in ([December],[January],[February])) as pvt
division December January February
AAA 50 200 60
BBB 100 150 70
  •  Tags:  
  • Related