简体   繁体   中英

get result where one column value is identical in two following rows

I want to select failed employees from employeeExam table where status column equals 0 for two following rows.

Result should be like this:

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

Here is what I did:
SQL Fiddle

To clarify more: when ordered by id , result should contains only exams' data which have the same course_id and employee_id and status = 0 under each other directly.

Please try this out and comment:

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 |

Just a portion of the SQL-code, to show the principle, although I doubt it fully extends your requirements. For example, this code doesn't check for consecutive failed attempts, only all attempts in general. It doesn't show any any rows of which the applicant has already passed an exam.

So for example: should one take an exam and get status 0, 0, 1, 0, 0; it would not show up, because applicant has passed at least one exam.

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

 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM