假设在MySQL 数据库中,有下面的数据表
表一:员工信息表(staff_info)
字段:Staff_code:员工工号;Staff_name:员工姓名;Department:所属部门
 
Staff_code Staff_name Department    
90001 路人甲 技术部    
90002 路人乙 技术部    
90003 路人丙 人事部    
90004 路人丁 人事部    
… … …  表二:上下班记录表(time_record)
字段:Staff_code:员工工号;arrive_time:上班时间;Leave_time:下班时间)
 
Staff_code arrive_time Leave_time    
9001 2010-07-02 09:32:33 2010-07-02 18:35:58    
9001 2010-07-05 09:45:03 2010-07-05 17:50:20    
9001 2010-08-03 09:55:01    
9002 2010-07-09 10:13:22 2010-07-09 19:48:00    
… … …  要求,使用一个SQL语句,查询出在7月份部门员工迟到3次及以上的部门,结果集包括部门名称、迟到次数。超过9点40分到达公司为迟到。帮助:
取分钟函数:datepart(minute, date_to_parse)
取小时函数:datepart(hour, date_to_parse)

解决方案 »

  1.   

    mysql> select a.department,count(b.arrive_time) from staff_info a,time_record b where a.staff_code=b.staff_code and time(b.arrive_time)>'09:40:00' group by a.department 
    having count(b.arrive_time)>=3;
      

  2.   

    select a.department,count(b.arrive_time) from staff_info a,time_record b where a.staff_code=b.staff_code and 
    time(b.arrive_time)>'09:40:00' and 
    month(b.arrive_time)=7 and
    year(b.arrive_time)=2010
     group by a.department 
    having count(b.arrive_time)>=3;