mysql从连接表获取结果

sy5wg1nm  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(262)

我有一个人和考试。

person

-------------
id  | name
-------------
1   | J.Doe
2   | Snow

exam
----------------------------------------------------
id | person_id | exam_no | exam_status | pass_date 
----------------------------------------------------
1  | 1         | 1       | PASS        | 2020-01-01
2  | 1         | 2       | PASS        | 2020-01-10
3  | 1         | 3       | PASS        | 2020-01-20
4  | 2         | 1       | PASS        | 2020-01-01
5  | 2         | 2       | NOT PASS    | NULL
6  | 2         | 3       | NOT PASS    | NULL

我想显示所有考试通过的数据,显示最新的考试通过日期。就像下面的表格

----------------------
person_id | pass_date
----------------------
1         | 2020-01-20
2         | NULL

什么查询得到它?请帮忙。谢谢!

vc6uscn9

vc6uscn91#

可以使用聚合和条件表达式:

select 
    person_id,
    case when max(exam_status = 'NOT PASS') = 0 then max(pass_date) end pass_date
from exam
group by person_id

注意,对于这个示例数据,不需要引入 person 表以获得所需的结果。

tct7dpnv

tct7dpnv2#

你的问题模棱两可。如果你想让某个人的所有考试都通过,那么我建议:

select p.*,
       (select max(e.pass_date)
        from exam e
        where e.person_id = p.id
        having sum(e.exam_status = 'PASS') = count(*)
       ) as pass_date
from person p;

但是,您也可能希望传递所有可能的示例。如果是:

select p.*,
       (select max(e.pass_date)
        from exam e
        where e.person_id = p.id
        having sum(e.exam_status = 'PASS') = ee.num_exams
       ) as pass_date     
from person p cross join
     (select count(distinct exam_no) as num_exams from exam) ee;

相关问题