假设我有一个表格,里面有学生的数据和他们的结果。
ID Result
1 PASS
2 PASS
3 PASS
3 FAIL
4 PASS
4 FAIL
4 FAIL
5 FAIL
5 FAIL
5 FAIL我想为每个学生选择一行,如果他们通过了,我希望pass行返回,但是如果没有,那么返回一个失败的行。
这是预期的结果:
ID Result
1 PASS
2 PASS
3 PASS
4 PASS
5 FAIL注:学生可以根据自己的意愿多次重新参加考试,直到他们通过考试或放弃考试。
谢谢。
发布于 2019-05-15 09:51:46
做一个GROUP BY。由于PASS (总是)大于FAIL,所以使用MAX()。
select ID, max(Result)
from tablename
group by ID发布于 2019-05-15 09:53:27
在这种情况下,一个获得最大结果的简单group by id就可以了:
select
id,
max(result) result
from tablename
group by id见演示。
结果:
> id | result
> -: | :-----
> 1 | PASS
> 2 | PASS
> 3 | PASS
> 4 | PASS
> 5 | FAIL 发布于 2019-05-15 09:44:25
使用相关的子查询和联合
select id,result from tbl
where result='pass'
union
select id,result from tbl
where not exists( select 1 from tbl t2 where t1.id=t2id
and result='pass')或者您可以使用row_number()解析函数
select id,result from
(select id,result,
row_number() over(partition by id order by case when result='pass' then 1 else 2 end) rn
) where rn=1https://stackoverflow.com/questions/56146235
复制相似问题