Quantcast
Channel: ฟอรัม Getting started with SQL Server
Viewing all articles
Browse latest Browse all 8428

How to write the query using pivot table?

$
0
0

Hi,

I am using the below query using pivot table.

 i have year column and employee id column in one table

Select [2013],[2014],Cast(CONVERT(NUMERIC(18,2),(CONVERT(NUMERIC(18,2),([2014]-[2013]))/CONVERT(NUMERIC(18,2),[2013])*100.00))as Varchar(50))+'%'AS Diff From
(Select [2013],[2014]
from
( Select Year,Count(EmployeeId)Cont from employee group by year) as sourcetable
Pivot ( sum(Cont) for [Year] in ([2013],[2014])) as pivotable )As A

 i want the output as follows i.e last two years as columns and count as the value

2013   2014

------   -----------

50       100

I am able to achieve this but i had to hard code 2013, 2014 in pivot. Can i get dynamically like

if the years present in table are 2011, 2012 then the out put should be like below

2011   2012

------   -----------

75       150

or if the years present in table are 2015, 2014 then

2015   2014

------   -----------

40      80

Regards


Gautam S


Viewing all articles
Browse latest Browse all 8428

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>