【问题标题】:Splits one column to multiple column according to data根据数据将一列拆分为多列
【发布时间】:2017-02-26 09:52:49
【问题描述】:

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

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 个月,我该怎么做?请帮帮我

【问题讨论】:

  • 你的问题是关于旋转,你可以在你的 DBMS 中搜索它并找到它;)。
  • 谁能举个例子??
  • 您的 DBMS 是什么? MySQL、SQL Server、甲骨文……?
  • 我的 RDBMS 是 SQL server 2008r2

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


【解决方案1】:

您可以使用这样的查询:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多