获得12个月的出勤记录

时间:2017-09-20 05:39:45

标签: sql sql-server sql-server-2008 pivot

这是我的表格结构

tbl_fullleaves:

leaveID(int)
EmpID(int)     
Normalleaves(double)
SSL(double)
MonthId(int)
YearId(int)

----
monthid =1 for jan , monthid = 2 for feb so on
yearid = 1 from where i started leaves incremental on yearly

表格中的数据:

Data Formate in sql

需要显示:

Empid Normalleave_jan SSl_jan Normalleave_feb SSl_feb Normalleave_mar SSl_mar

2        3.25          4.5      3.75            0        0              4.5 

1 个答案:

答案 0 :(得分:0)

这是在SQL中转置数据最流行的方法:

select EmpID,
   max(case when MonthID = 1 then NormalLeave end) as NormalLeave_jan,
   max(case when MonthID = 1 then [SSL] end) as SSL_jan,
   max(case when MonthID = 2 then NormalLeave end) as NormalLeave_feb,
   max(case when MonthID = 2 then [SSL] end) as SSL_feb,
   max(case when MonthID = 3 then NormalLeave end) as NormalLeave_mar,
   max(case when MonthID = 3 then [SSL] end) as SSL_mar,
   max(case when MonthID = 4 then NormalLeave end) as NormalLeave_apr,
   max(case when MonthID = 4 then [SSL] end) as SSL_apr,
   max(case when MonthID = 5 then NormalLeave end) as NormalLeave_may,
   max(case when MonthID = 5 then [SSL] end) as SSL_may,
   max(case when MonthID = 6 then NormalLeave end) as NormalLeave_jun,
   max(case when MonthID = 6 then [SSL] end) as SSL_jun,
   max(case when MonthID = 7 then NormalLeave end) as NormalLeave_jul,
   max(case when MonthID = 7 then [SSL] end) as SSL_jul,
   max(case when MonthID = 8 then NormalLeave end) as NormalLeave_aug,
   max(case when MonthID = 8 then [SSL] end) as SSL_aug,
   max(case when MonthID = 9 then NormalLeave end) as NormalLeave_sep,
   max(case when MonthID = 9 then [SSL] end) as SSL_sep,
   max(case when MonthID = 10 then NormalLeave end) as NormalLeave_oct,
   max(case when MonthID = 10 then [SSL] end) as SSL_oct,
   max(case when MonthID = 11 then NormalLeave end) as NormalLeave_nov,
   max(case when MonthID = 11 then [SSL] end) as SSL_nov,
   max(case when MonthID = 12 then NormalLeave end) as NormalLeave_dec,
   max(case when MonthID = 12 then [SSL] end) as SSL_dec
from tbl_fullleaves
group by EmpID