请建议使用SQL查询来获取
“如果学生在多个科目中得分相同,则学生和相应科目列表中的学生得分相同”
例如
Student Subject Score
John Science 80
John Maths 80
John English 80
John French 80
Peter Science 85
Peter Maths 70
Peter English 70
Peter French 70
Mathews French 70
Expected Result :
John Science
John Maths
John English
John French
Peter Maths
Peter English
Peter French
尝试过 -
select person , subject where person in
( select person , score , count(score) group by person , score having count(score) > 1 )
但是出现了“彼得科学”,这不是必需的。
请协助。
由于
答案 0 :(得分:2)
尝试:
select person , subject
from table t
join
( select person , score , count(score)
from table
group by person , score having count(score) > 1
) foo
on t.person = foo.person
where t.person = foo.person
and t.score = foo.score
您的查询不起作用的原因(除了不包括表格): 您的内部查询是选择符合您条件的学生和分数。但是你的外部询问是为符合标准的所有学生选择所有,这就是为什么要包括“彼得科学”的原因。因此,您需要将外部查询中的结果限制为仅匹配所有条件的结果。
答案 1 :(得分:0)
您应该告诉我们您使用的是哪种RDBMS。但这应该适用于所有地方:
select
t.*
from <tableName> t
join (
select
student, score
from <tableName>
group by
student, score
having count(*)>1
) x
on t.student=x.student
and t.score=x.score
您的查询中遗漏了FROM <tableName>
。
答案 2 :(得分:0)
试试这个:
select student, subject
from Person
where student + cast(score as varchar(20)) in
(
select student + cast(score as varchar(20)) from Person group by student,score having count(score) > 1
)
答案 3 :(得分:0)
您可以像示例一样实现此目标自联接表:
SELECT
t.Student,
t.Subject,
t.Score
FROM Table1 AS t
JOIN
(
SELECT Student, Score FROM Table1 GROUP BY Student, Score HAVING COUNT(*) > 1
) AS t1 ON t.Student = t1.Student AND t.Score = t1.Score
您可以在此处找到测试数据和创建表的完整示例: