Sunday, 3 May 2015

PIVOT Table query

create table  dbo.Salary_hist(EMPNAME nvarchar(100),CTC decimal(18,2),DateAdded datetime)

insert into Salary_hist values('Ram','300000','2015-01-01')
insert into Salary_hist values('Ram','30000','2014-01-01')
insert into Salary_hist values('Ram','3000','2013-01-02')
insert into Salary_hist values('Ram','2700','2013-01-01')
insert into Salary_hist values('Ram','300','2012-01-01')
insert into Salary_hist values('Ram','30','2011-01-01')

SELECT EMPNAME,[2015],[2014],[2013],[2012],[2011]
FROM
(
    SELECT DISTINCT EMPNAME,MAX(CTC) OVER(PARTITION BY EMPNAME,YEAR(DATEADDED))MAXCTC,
    YEAR(DATEADDED)PERIOD
    FROM Salary_hist
)S
PIVOT
(
    MIN(MAXCTC)
    FOR PERIOD IN([2015],[2014],[2013],[2012],[2011])
)P

No comments:

Post a Comment