2

刚面试完回来。我有这个问题:

我有 3 列的表Student, Profession, Mark

每个学生学习超过 1 个专业。

我需要编写 SQL Server 查询,该查询返回数学和物理都得分为 100 的学生的不同姓名(AND)

知道如何实施这个问题吗?

这是我的尝试:(它并不完美......)

SELECT *  FROM Marks
CROSS APPLY
  (SELECT Student_Name  WHERE (Profession='Physics')AND(Mark=100)
   UNION 
   SELECT Student_Name WHERE (Profession='Mathematics')AND(Mark=100)
  )
  AS Question
4

7 回答 7

10

这可以通过 a 来完成JOIN,但我更喜欢在可能的情况下进行单次扫描。

SELECT
   M.Student_Name
FROM
   dbo.Marks M
WHERE
   M.Profession IN ('Physics', 'Mathematics')
   AND M.Mark = 100
GROUP BY
   M.Student_Name
HAVING
   Count(DISTINCT M.Profession) = 2
;

另一方面,如果表在Profession和/或Mark列上有索引,则最好进行连接:

SELECT DISTINCT
   P.Student_Name
FROM
   dbo.Marks P
   INNER JOIN dbo.Marks M
      ON P.Student_Name = M.Student_Name
WHERE
   P.Profession = 'Physics'
   AND P.Mark = 100
   AND M.Profession = 'Mathematics'
   AND M.Mark = 100
;
于 2013-06-14T22:07:18.923 回答
1
Select Student from Marks where Profession = 'Mathematics' and marks = 100
intersect
Select Student from Marks where Profession = 'Physics' and marks = 100
于 2016-09-18T00:59:37.750 回答
0

你也可以这样做:

SELECT DISTINCT Student_Name
FROM Marks
WHERE (Profession = 'Physics' AND Mark = 100)
   AND Student_Name IN (SELECT Student_Name
                        FROM Marks
                        WHERE Profession = 'Mathematics' AND Mark = 100)
于 2013-06-14T22:09:26.277 回答
0
select a.student
from
   (select student, 
   count(distinct profession) as profession_count,
   avg(mark) as avg_mark
   from marks
   where profession in ('mathmatics', physics')
   group by student) a
where a.profession_count >= 2
and a.avg_mark = 100
于 2013-11-01T02:58:27.133 回答
0

SELECT DISTINCT name FROM a WHERE prof = 'phy' AND mar = '100' AND name IN (SELECT DISTINCT name FROM a WHERE prof = 'math' AND mar = '100' )

于 2014-05-06T17:45:38.713 回答
0
select t.student_name
from tab t
join tab p on t.student_name = p.student_name and 
    p.Profession='Physics' AND p.Mark=100
where t.Profession='Mathematics' AND t.Mark=100
于 2013-06-14T22:06:55.417 回答
0

一个简单的内部连接就可以了。

SELECT physics.Student FROM 
Marks physics
JOIN Marks math ON physics.Student = math.Student
WHERE physics.Profession='Physics'
AND math.Profession='Math'
AND physics.Mark = 100
AND math.Mark = 100
于 2013-06-14T22:08:46.910 回答