2005的实现方法:
declare @ta table(编号 int,人员 varchar(5), 年份 int,月份 int ,[1号] varchar(5), [2号] varchar(5),[3号] varchar(5),[4号] varchar(5))
insert @ta select 1, '张三',2006, 1, '正常', '迟到', '迟到', '事假'
union all select 2, '张三', 2006, 2, '迟到', '事假', '正常', '正常'
union all select 3, '李四', 2006, 3, '正常', '正常', '正常', '正常'
union all select 4, '王五', 2007, 5, '正常', '正常','正常', '正常'select 编号,人员,年份,月份,[正常],[迟到],[事假]
from (
select 编号,人员,年份,月份,原因,Orders
from (select * from @ta)ta
unpivot
(orders for [原因] in([1号],[2号],[3号],[4号])
)as tb
)tmp
pivot
(count(原因) for Orders in([正常],[迟到],[事假])
)tmp2
(4 行受影响)
编号          人员    年份          月份          正常          迟到          事假
----------- ----- ----------- ----------- ----------- ----------- -----------
1           张三    2006        1           1           2           1
2           张三    2006        2           2           1           1
3           李四    2006        3           4           0           0
4           王五    2007        5           4           0           0(4 行受影响)

解决方案 »

  1.   

    2000实现:
    declare @ta table(编号 int,人员 varchar(5), 年份 int,月份 int ,[1号] varchar(5), [2号] varchar(5),[3号] varchar(5),[4号] varchar(5))
    insert @ta select 1, '张三',2006, 1, '正常', '迟到', '迟到', '事假'
    union all select 2, '张三', 2006, 2, '迟到', '事假', '正常', '正常'
    union all select 3, '李四', 2006, 3, '正常', '正常', '正常', '正常'
    union all select 4, '王五', 2007, 5, '正常', '正常','正常', '正常'
    select 编号,人员,年份,月份,
    [正常]=sum(case 原因 when '正常' then 1 else 0 end)
    ,[迟到]=sum(case 原因 when '迟到' then 1 else 0 end)
    ,[事假]=sum(case 原因 when '事假' then 1 else 0 end)
    from 
    (select 编号,人员,年份,月份,[1号]as 原因 from @ta
    union all 
    select 编号,人员,年份,月份,[2号] from @ta
    union all 
    select 编号,人员,年份,月份,[3号] from @ta
    union all 
    select 编号,人员,年份,月份,[4号] from @ta
    )tmp
    group by 编号,人员,年份,月份(4 行受影响)
    编号          人员    年份          月份          正常          迟到          事假
    ----------- ----- ----------- ----------- ----------- ----------- -----------
    1           张三    2006        1           1           2           1
    2           张三    2006        2           2           1           1
    3           李四    2006        3           4           0           0
    4           王五    2007        5           4           0           0(4 行受影响)
      

  2.   

    select 人员 , 年份 , 月份
           sum(case when 情况='事假' then 1 else 0 end) as 事假天数,
           sum(case when 情况='迟到' then 1 else 0 end) as 迟到天数
    from
    (
      select 人员 , 年份 , 月份 , 1号 from tb
      union all
      select 人员 , 年份 , 月份 , 2号 from tb
      union all
      select 人员 , 年份 , 月份 , 3号 from tb
      ....
      select 人员 , 年份 , 月份 , 31号 from tb
    ) t
    group by 人员 , 年份 , 月份