【发布时间】:2018-03-27 21:26:29
【问题描述】:
我正在尝试编写一个查询,该查询将提取已通过测试 1 到 3 并且未通过测试 4 的学生。
学生可以重新参加考试,因此可能会有不及格的记录,然后是一些考试的通过记录,例如下面的 student_id = 2。
这样的表设置 -
test_id | student_id | status | completed_on
--------+------------+---------+------------
1 | 1 | passed | 2018-03-24
2 | 1 | passed | 2018-03-25
3 | 1 | passed | 2018-03-26
4 | 1 | failed | 2018-03-27
1 | 2 | failed | 2018-03-24
1 | 2 | passed | 2018-03-25
2 | 2 | passed | 2018-03-26
3 | 2 | passed | 2018-03-27
4 | 2 | failed | 2018-03-27
在这种情况下,查询应该同时提取 student_id 1 和 2
我试过了,但显然没有用 -
select *
from table
where (test_id = 1 and status = 'passed')
and (test_id = 2 and status = 'passed')
and (test_id = 3 and status = 'passed')
and (test_id = 4 and status = 'failed')
【问题讨论】:
-
假设一旦测试通过,就不会再次尝试,您可以获得每组 test_id 和 student_id 的 max(completed_on),然后只检查这些行。跨度>
-
@clinomaniac 说,接受是一个日期;如果重拍发生在同一日期,则不能保证该日期的最大值是您想要的记录。理想情况下,该表还应该有一个自动递增的主键 - 然后您可以在组内使用其中的最大值
-
一条记录不能是 test_ID=1 和 test_ID = 2。所以
ands 需要是or's 然后你需要计算具有 count = 4 分组的唯一测试通过 student_ID 但如果测试 4 进行了两次,第一次失败然后通过...你会得到它而不想要它吗? -
不参加考试 4 算不算失败?因此,如果一个人没有 Test_4 记录,但他们通过了 1-3 次...您希望该学生返回吗?