通过和失败记录相同的测试

q9rjltbz  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(270)

这里是sql新手。我试着搜索,但找不到这个场景。
对于一个特定的考试,学生可以有多个记录(通过,失败,不显示,放弃)。

results table

Student_ID  Exam_ID    Status     Time_stamp

   1          A       Passed      2018-05-01
   2          A       Failed      2018-05-01
   2          A       Passed      2018-05-05  
   3          A       No-Show     2018-05-01
   3          A       Failed      2018-05-05
   4          A       Passed      2018-05-01
   4          A       Failed      2018-05-25

如何构造sql查询以显示已通过的学生列表,如果未通过,则按日期显示最新状态。
例如,在示例数据中,student\u id 1=通过,student\u id 2=通过(one pass record=通过),student\u id 3=失败(no pass records,failed becomes after no show),student\u id 4=通过(考试中的one pass record=通过,ignore later fail)
到目前为止我试过这个-

SELECT * 
FROM results
WHERE Status = "Passed"

但这显然不包括未通过的状态。
非常感谢你的帮助。

waxmsbnn

waxmsbnn1#

您也可以使用等级:

SELECT student_id, exam_id, status, time_stamp
FROM
(
SELECT *, RANK() OVER(PARTITION BY student_id ORDER BY time_stamp DESC) AS rnk
FROM t
) sub
WHERE status = 'Passed'
OR (rnk = 1
    AND NOT EXISTS
    (SELECT 1
     FROM t t2
     WHERE status = 'Passed'
     AND t2.student_id = sub.student_id))

所以逻辑是:取状态为通过的记录,或者(1)测试是该学生最近的一次测试,(2)该学生没有通过测试。

ktecyv1j

ktecyv1j2#

优化的版本 with t (Student_ID, Exam_ID, Status, Time_stamp) as ( select 1, 'A', 'Passed', '2018-05-01' union all select 2, 'A', 'Failed', '2018-05-01' union all select 2, 'A', 'Passed', '2018-05-05' union all select 3, 'A', 'No-Show', '2018-05-01' union all select 3, 'A', 'Failed', '2018-05-05' union all select 4, 'A', 'Passed', '2018-05-01' union all select 4, 'A', 'Failed', '2018-05-25') select * from (select *,row_number() over(PARTITION BY student_id,exam_id order by case when status='Passed' then 1 when status='Failed' then 2 when status='No-Show' then 3 end, time_stamp desc) r from t) result where r=1

ltqd579y

ltqd579y3#

这里有一种方法 union all :

select r.*
from results r
where r.status = 'Passed'
union all
select t.*
from results r
where not exists (select 1 
                  from results r2
                  where r2.student_id = r.student_id and
                        r2.exam_id = r.exam_id and
                        r2.status = 'Passed'
                 ) and
      r.time_stamp = (select max(r2.time_stamp
                      from results r2
                      where r2.student_id = r.student_id and
                            r2.exam_id = r.exam_id 
                     );
6l7fqoea

6l7fqoea4#

下面的链接几乎相同。运用一些策略,你就会得到答案
sql查询以查找所有记录的特定值

相关问题