获取结果,其中一列值在后续两行中相同

时间:2013-01-20 14:10:00

标签: mysql sql

我想从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_idemployee_id以及status = 0的数据。

3 个答案:

答案 0 :(得分:0)

请尝试一下并发表评论:

SQLFIDDLE DEMO

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 |

答案 1 :(得分: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 Fiddle

答案 2 :(得分: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;