0

我想从employeeExam表中选择失败的员工,其中status列等于0以下两行。

结果应该是这样的:

ID  COURSE_ID  EMPLOYEE_ID  DEGREE  DATE                             STATUS  NUMOFTAKINGEXAMS
4   2          4            17      January, 15 2013 00:00:00+0000   0       2

这是我所做的:
SQL Fiddle

为了进一步澄清:当按 排序时id,结果应该只包含考试的数据,这些数据直接在彼此下具有相同的course_idandemployee_id和= 0。status

4

3 回答 3

0
 SELECT a.*
   FROM
      ( SELECT x.*
             , COUNT(*) rank
          FROM employeeExam x 
          JOIN employeeExam y 
            ON y.course_id = x.course_id 
           AND y.employee_id = x.employee_id 
           AND y.date <= x.date 
         GROUP 
           BY id 
      ) a
   JOIN
      ( SELECT x.*
             , COUNT(*) rank
          FROM employeeExam x 
          JOIN employeeExam y 
            ON y.course_id = x.course_id 
           AND y.employee_id = x.employee_id 
           AND y.date <= x.date
         GROUP 
           BY id 
      ) b
     ON b.course_id = a.course_id
    AND b.employee_id = a.employee_id
    AND b.status = a.status
    AND b.rank = a.rank - 1
  WHERE a.status = 0;
于 2013-01-21T09:55:01.330 回答
0

请尝试一下并发表评论:

SQLFIDDLE 演示

set @sum:=0;
set @id:=0;     

select distinct x.empid, x.degree, x.date, x.status
from (
select @sum:= (case when status=0
               and @id = employee_id then @sum+1
               else 1 end)
as sm,  @id:=employee_id as empid, degree, date, status
from employeeexam
order by employee_id)x
where x.sm >= 2
;

| EMPID | DEGREE |                           DATE | STATUS |
------------------------------------------------------------
|     2 |      5 | January, 16 2013 00:00:00+0000 |      0 |
|     3 |      6 | January, 16 2013 00:00:00+0000 |      0 |
|     4 |     15 | January, 14 2013 00:00:00+0000 |      0 |
于 2013-01-20T14:38:33.507 回答
0

只是 SQL 代码的一部分,以显示原理,尽管我怀疑它是否完全扩展了您的要求。例如,此代码不检查连续失败的尝试,一般只检查所有尝试。它不显示申请人已经通过考试的任何行。

例如:如果一个人参加考试并获得状态 0、0、1、0、0;它不会出现,因为申请人至少通过了一项考试。

SELECT course_id, employee_id, MAX(degree), status, COUNT(id) NumExamsTaken
FROM employeeExam
GROUP BY course_id, employee_id
HAVING COUNT(id) >= 2 AND SUM(status) = 0;

SQL小提琴

于 2013-01-20T14:39:09.933 回答