我有这张桌子
name | prof |grade
------------------------
yossi math 100
tami math 70
yossi phisic 100
tami phisic 100
oren math 100
oren phisic 80
dor history 70
查询应该返回数学和phisic等级为100的学生的姓名 正确的解决方案是yossi 我使用了以下
SELECT name FROM [dbo].[Class_grade]
where prof in ('math', 'phisic') and grade = 100
但是为什么会返回更多的名字? 什么是正确的查询? 感谢
答案 0 :(得分:6)
select name
from Class_Grade
where grade = 100 and
prof in ('math', 'phisic')
group by name
having count(distinct prof) = 2
按name
分组,并使用having
过滤掉行。确保计算prof
的不同出现次数。在这种情况下它是2,因为你的in子句中有2个值。
答案 1 :(得分: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 FIDDLE 强>
答案 2 :(得分:0)
分组,并使suure得到两行
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
答案 3 :(得分:0)
试试这个
SELECT name FROM Class_grade
WHERE prof IN ('math', 'phisic') AND grade=100
GROUP BY name
HAVING COUNT(name) > 1
答案 4 :(得分:0)
OP没有说明一些细节:
如果我们假设一个学生可以在同一个科目中有多个成绩,那么HAVING COUNT(*)
个条款中的许多其他答案都是错误的。 Mikael Eriksson's answer满足了这个假设,并且它可能比我的下面的解决方案更高效(尽管功能也有所不同):
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
math
和phisic
科目的学生,即使他们每个科目的成绩可能超过一个。 See here
答案 5 :(得分: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
尽量不要使用distinct,这是一个糟糕的编码
答案 6 :(得分:-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)