我正在尝试编写SQL查询,该查询返回的主主题(学生表)是唯一的subject_id(结果表)。
结果表具有列(学生ID,科目ID,标记)
我的查询:
SELECT r.subject_id
FROM result r
JOIN student s ON r.student_id = s.student_id
WHERE s.primary_skill IN (SELECT DISTINCT primary_skill
FROM student)
GROUP BY 1;
我有这个结果:
subject_id
1
2
3
4
5
6
7
8
9
10
1001
但是我应该只返回ID 1001,因为只有该科目具有唯一的学生primary_skill,其他ID都重复了主要技能。
我在做什么错?它如何改善?
答案 0 :(得分:1)
请尝试以下操作:
select result.subject_id from student
join result on student.id =result.student_id where
student.primary_skill in
(select primary_skill from student group by primary_skill having COUNT(*)=1)
答案 1 :(得分:0)
如果我理解这项权利,那么您只想为只有一种技能的学生取得成绩。您可以使用GROUP BY
和HAVING
子句来检查技能计数是否等于一。
SELECT r.subject_id
FROM result r
INNER JOIN (SELECT s.student_id
FROM student s
GROUP BY s.student_id
HAVING count(DISTINCT s.primary_skill) = 1) x
ON x.student_id = r.student_id;