8

我需要执行一个相对容易解释但(鉴于我的技能有限)很难编写 SQL 查询。

假设我们有一个类似于这个的表:

 exam_no | name | surname | result | date
---------+------+---------+--------+------------
 1       | John | Doe     | PASS   | 2012-01-01
 1       | Ryan | Smith   | FAIL   | 2012-01-02 <--
 1       | Ann  | Evans   | PASS   | 2012-01-03
 1       | Mary | Lee     | FAIL   | 2012-01-04
 ...     | ...  | ...     | ...    | ...
 2       | John | Doe     | FAIL   | 2012-02-01 <--
 2       | Ryan | Smith   | FAIL   | 2012-02-02
 2       | Ann  | Evans   | FAIL   | 2012-02-03
 2       | Mary | Lee     | PASS   | 2012-02-04
 ...     | ...  | ...     | ...    | ...
 3       | John | Doe     | FAIL   | 2012-03-01
 3       | Ryan | Smith   | FAIL   | 2012-03-02
 3       | Ann  | Evans   | PASS   | 2012-03-03
 3       | Mary | Lee     | FAIL   | 2012-03-04 <--

请注意,exam_no并且date不一定像我选择的示例中所期望的那样相关。

现在,我需要做的查询如下:

  • 从最近的考试 ( exam_no= 3) 中找出所有不及格的学生 ( John Doe,Ryan SmithMary Lee)。
  • 对于这些学生中的每一个,找出连续不及格的考试中第一批的日期。另一种说法是:对于这些学生中的每一个,找出他们最后一次通过考试之后的第一次失败考试的日期。(查看表中的箭头)。

结果表应该是这样的:

 name | surname | date_since_failing
------+---------+--------------------
 John | Doe     | 2012-02-01
 Ryan | Smith   | 2012-01-02
 Mary | Lee     | 2012-03-04

我怎样才能执行这样的查询?

感谢您的时间。

4

4 回答 4

4

您可以利用这样一个事实,即如果某人通过了最近一次考试,那么他们自最近一次通过以来就没有通过任何考试:因此问题归结为发现自最近一次通过以来的第一次考试失败:

SELECT   name, surname, MIN(date) date_since_fail
FROM     results NATURAL LEFT JOIN (
  SELECT   name, surname, MAX(date) lastpass
  FROM     results
  WHERE    result = 'PASS'
  GROUP BY name, surname
) t
WHERE    result = 'FAIL' AND date > IFNULL(lastpass,0)
GROUP BY name, surname

sqlfiddle上查看。

于 2012-07-04T13:52:06.347 回答
0

我应该使用一个子查询来获取上次通过的考试,例如:

SET @query_exam_no = 3;
SELECT
 name,
 surname,
 MIN(IF(date > last_passed_exam, date, NULL)) AS date_failing_since
FROM
 exam_results
 LEFT JOIN (
  SELECT
   name,
   surname, 
   MAX(date) AS last_passed_exam 
  FROM exam_results 
  WHERE result = 'PASS' 
  GROUP BY name, surname
 ) AS last_passed_exams USING (name, surname)
HAVING
 MAX(IF(exam_no = @query_exam_no, result, NULL)) = 'FAIL'
GROUP BY name, surname
于 2012-07-04T13:45:19.177 回答
0

这就够了:

select t.name,
       t.surname,
       t.date as 'date_since_failing'
from tablename t
inner join
(
    select name,
           surname,
           max(exam_no) as exam_no
    from tablename
    group by name, surname
    having min(result) = 'FAIL'
) aux on t.name = aux.name and t.surname = aux.surname and t.exam_no = aux.exam_no
于 2012-07-04T13:48:17.437 回答
0

你所要求的条件是没有用的,没有它你就做不到。这是工作示例。

select
  e.name,
  e.sur_name,
  min(e.date) as `LastFailed`
from exams as e
where e.result = 'Fail'
group by e.name
    order by e.name 

这产生了这个结果

name            sur_name    LastFailed
Ann         Evans       2012-02-03
John        Doe         2012-02-01
Mary        Lee         2012-01-04
Ryan        Smith       2012-01-02
于 2012-07-04T13:51:18.897 回答