0

我有这张桌子

name   | prof      |grade
------------------------
yossi   math     100
tami    math     70
yossi   phisic   100
tami    phisic   100
oren    math     100
oren    phisic   80
dor     history  70

查询应返回数学和物理成绩为 100 的学生的姓名正确的答案是 yossi 我使用了以下内容

SELECT name FROM [dbo].[Class_grade]
where prof in ('math', 'phisic') and grade = 100

但它返回更多名称,为什么?什么是正确的查询?谢谢

4

7 回答 7

6
select name
from Class_Grade
where grade = 100 and
      prof in ('math', 'phisic')
group by name
having count(distinct prof) = 2

Group by name and filter out the rows using having. Make sure you count the distinct occurrences of prof. In this case it is 2 because you have 2 values in your in clause.

于 2013-06-13T08:58:31.887 回答
1

早些时候我错误引用了Question

您可以使用Group by caluse

SELECT name FROM [Class_grade]
where prof in ('math', 'phisic') and grade = 100
group by (name)
having count(1)=2

SQL 小提琴

于 2013-06-13T08:52:48.673 回答
0
            select Class_grade.name
            from Class_grade
            inner join Class_grade Class_grade2
            on Class_grade.Name = Class_grade2.name
            where Class_grade.Prof = 'math' and Class_grade.grade = 100
            and Class_grade2.prof = 'phisic' and Class_grade2.grade = 100
            group by Class_grade.Name

尽量不要使用不同的,它的编码很差

于 2013-06-13T14:24:44.793 回答
0

尝试这个

SELECT name FROM Class_grade
WHERE prof IN ('math', 'phisic') AND grade=100
GROUP BY name
HAVING COUNT(name) > 1
于 2013-06-13T09:01:37.707 回答
0

分组并确保你得到两行

SELECT name 
FROM Class_grade
WHERE prof in ('math', 'phisic') and grade = 100
GROUP BY name
HAVING count(*) = 2 

http://www.sqlfiddle.com/#!3/9308c/6

编辑 如果同一个学生在一个科目中可以有超过一个 100%,你可以得到不同的成绩

SELECT name 
FROM (
  SELECT DISTINCT name, prof, grade
  FROM Class_grade
  WHERE prof in ('math', 'phisic') and grade = 100
) class_grade
GROUP BY name
HAVING count(*) = 2 

http://www.sqlfiddle.com/#!3/79fd0/11

于 2013-06-13T08:59:37.753 回答
0

OP没有说明一些细节:

  • 表上的主键是什么(即同一学生同一科目可以有多行)
  • 当有多个符合条件的学生时,预期的结果是什么。

如果我们假设一个学生在同一科目中可以有多个成绩,那么这些HAVING COUNT(*)条款中的许多其他答案都是错误的。Mikael Eriksson 的回答满足了这个假设,并且它可能比我下面的解决方案更高效(虽然功能也有点不同):

SELECT DISTINCT name FROM [dbo].[Class_grade] cg1
WHERE EXISTS (
  SELECT 1 FROM [dbo].[Class_grade] cg2
  WHERE cg2.name = cg1.name
  AND cg2.prof = 'math'
  AND cg2.grade = 100)
AND EXISTS (
  SELECT 1 FROM [dbo].[Class_grade] cg2
  WHERE cg2.name = cg1.name
  AND cg2.prof = 'phisic'
  AND cg2.grade = 100)
AND NOT EXISTS (
  SELECT 1 FROM [dbo].[Class_grade] cg2
  WHERE cg2.name = cg1.name
  AND cg2.prof in ('math','phisic')
  AND cg2.grade < 100)

上述代码的不同之处在于,它只会选择只有和科目grade = 100的学生,即使他们每个科目可以有一个以上的成绩。见这里mathphisic

于 2013-06-13T10:28:27.073 回答
-2

尝试这个:

SELECT DISTINCT name  FROM [dbo].[Class_grade] where prof in ('math', 'phisic') and grade = 100

这也可以:

SELECT DISTINCT name FROM [dbo].[Class_grade] where (prof = 'math' and grade = 100) OR (prof = 'phisics' and grade = 100)
于 2013-06-13T08:50:53.400 回答