求职面试

时间:2013-06-14 22:00:32

标签: sql sql-server

刚从求职面试中回来。我有这个问题:

我有3列Student, Profession, Mark

的表格

每个学生都学习一门以上的专业。

我需要编写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

7 个答案:

答案 0 :(得分:10)

这可以使用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
;

答案 1 :(得分:1)

Select Student from Marks where Profession = 'Mathematics' and marks = 100
intersect
Select Student from Marks where Profession = 'Physics' and marks = 100

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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)

答案 5 :(得分: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

答案 6 :(得分:0)

SELECT DISTINCT name FROM WHERE prof =' phy'并且mar =' 100'并命名IN(SELECT DISTINCT name FROM WHERE prof =' math' AND mar =' 100')