数据库中有三个表,表的字段及表中现有数据如下:ID sID  eID(表名为dtStaffAttendance)
1  101  5  
2  103  5
3  103  5
4  103  5
5  103  2
6  103  2
7  103  2eID   eName (表名为dtEvent)
1     正常
2     迟到
3     早退
4     旷工
5     补录sID   sName   sex 
101    张三    男
103    李四    女我要输出地效果是
sID  sName  sex  正常次数  迟到次数  早退次数  旷工次数  补录次数
101   张三  男     0          0          0        0          1
103   李四  女     0          3          0        0          3请问这个数据库语句怎么写啊?

解决方案 »

  1.   

    if OBJECT_ID('ta') is not null
    drop table ta
    go
    create table ta (ID int ,sID int ,eID int)
    insert into ta
    select 1, 101, 5 union all  
    select 2, 103, 5 union all  
    select 3, 103, 5 union all  
    select 4, 103, 5 union all  
    select 5, 103, 2 union all  
    select 6, 103, 2 union all  
    select 7, 103, 2
    if OBJECT_ID('tb') is not null
    drop table tb
    go
    create table tb (eID int,eName varchar(4))
    insert into tb
    select 1, '正常' union all  
    select 2, '迟到' union all  
    select 3, '早退' union all  
    select 4, '旷工' union all  
    select 5, '补录'
    if OBJECT_ID('tc') is not null
    drop table tc
    go
    create table tc (sID int,sName varchar(4),sex varchar(2))
    insert into tc
    select 101, '张三', '男' union all
    select 103, '李四', '女'
    --select * from ta
    --select * from tb
    --select * from tcselect c.sID,c.sName,c.sex, 正常次数=SUM( case b.eName when '正常' then 1 else 0 end ),
                                迟到次数=SUM( case b.eName when '迟到' then 1 else 0 end ),
                                早退次数=SUM( case b.eName when '早退' then 1 else 0 end ),
                                旷工次数=SUM( case b.eName when '旷工' then 1 else 0 end ),
                                补录次数=SUM( case b.eName when '补录' then 1 else 0 end )
    from tc c join ta a on c.sID=a.sID
         join tb b on a.eID=b.eID
    group by c.sID,c.sName,c.sexsID sName sex 正常次数 迟到次数 早退次数 旷工次数 补录次数
    101 张三 男 0 0 0 0 1
    103 李四 女 0 3 0 0 3