根据数据将一列拆分为多列

时间:2017-02-26 09:52:50

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

我有一张表,其中包含一年的std出勤数据

AttID   Present absent. leave sick month  StdRegNo
1.      23      1       0     0    JAN.   1
2.      25      0       0     0    JAN.   2
3.      23      0       0     0    MAR.   1
4.      21      3       0     1    MAR.   2
SO ON.......

我希望得到如下观点的结果:

StdReq month  P   A   L    S    month  P   A    L    S
1.     Jan.   23  1   0    0    Mar    23  0    0    0
2.     Jan.   25  0   0    0    Mar    21  3    0    1

我需要这个观点12个月我该怎么办?请帮帮我

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询:

select StdRegNo
    -- January info
    ,max(case when [month] = 'JAN' then Present end) JAN_P
    ,max(case when [month] = 'JAN' then [absent] end) JAN_A
    ,max(case when [month] = 'JAN' then leave end) JAN_L
    ,max(case when [month] = 'JAN' then sick end) JAN_S
    -- March info
    ,max(case when [month] = 'MAR' then Present end) MAR_P
    ,max(case when [month] = 'MAR' then [absent] end) MAR_A
    ,max(case when [month] = 'MAR' then leave end) MAR_L
    ,max(case when [month] = 'MAR' then sick end) MAR_S
    -- And so on ...
from yourTable
group by StdRegNo;