-1

请建议一个 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 )

但是在这个“彼得科学”中出现了,这不是必需的。

请协助。

谢谢

4

4 回答 4

3

尝试:

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

您的查询不起作用的原因(除了不包括表格):您的内部查询正在选择符合您条件的学生和分数。但是您的外部查询是为所有符合条件的学生选择所有内容,这就是包含“彼得科学”的原因。因此,您需要将外部查询中的结果限制为仅与您的所有条件匹配的结果。

于 2013-03-22T12:37:00.597 回答
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

您可以在此处找到包含测试数据和创建表的完整示例:

http://sqlfiddle.com/#!2/61f02/8

于 2013-03-22T12:58:37.617 回答
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>,您的查询中缺少。

于 2013-03-22T12:33:14.293 回答
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 
)
于 2013-03-22T12:38:43.530 回答