这个是我写的sql语句
select count(考勤天数),员工ID,月份  from  考勤表 group by   员工ID,月份;下边这个是查询出来的结果:
   考勤天数     员工ID     月份
         28          A         4
         26          A         3
         25          A         2
         28          B         3
         26          B         2
         27          C         4
         30          C         3
         27          C         2我想让它查询出这样的显示结果怎么做呢?
      员工ID    4月     3月      2月
          A       28     26       25
          B       0      28       26
          C       27     30       27

解决方案 »

  1.   

    select
      员工ID,
       max(case 月份 when 4 then 考勤天数 else 0 end) as 4月,
       max(case 月份 when 3 then 考勤天数 else 0 end) as 3月,
       max(case 月份 when 2 then 考勤天数 else 0 end) as 2月
    from
      tb
    group by
      员工ID
      

  2.   

    只是月份的话  一般做法都是一个一个判断 然后合计  也可以使用存储 动态sql拼接起来 
      

  3.   


     --> 测试数据:[test]
    if object_id('[test]') is not null drop table [test]
    create table [test]([考勤天数] int,[员工ID] varchar(1),[月份] int)
    insert [test]
    select 28,'A',4 union all
    select 26,'A',3 union all
    select 25,'A',2 union all
    select 28,'B',3 union all
    select 26,'B',2 union all
    select 27,'C',4 union all
    select 30,'C',3 union all
    select 27,'C',2--我写一个动态的declare @str varchar(2000)
    set @str=''
    select 
    @str=@str+',['+LTRIM([月份])+'月]=max(case when [月份]='
    +ltrim([月份])+' then [考勤天数] else 0 end)'
    from 
    [test]
    group by
    [月份]
    exec('select [员工ID]'+@str+' from test group by [员工ID]')/*
    员工ID 2月 3月 4月
    -------------------------------
    A 25 26 28
    B 26 28 0
    C 27 30 27
    */
      

  4.   


    大侠,您还在上班吗,这个结果要是用oracle怎么实现呢。