SQL:为什么我用下面的两个查询没有得到相同的输出?

SQL: Why do I not get the same output with the two queries below?

我正在寻找获得所有可能不同成绩的学生。如果你得到 18 分,你就通过了这门课程,最高分是 30 分。因此,如果你得到了 13 个不同的分数,而这些分数都高于 17 分,那么你就获得了所有可能的及格分数。第一个查询 returns 0 行,第二个查询 returns 一个学生已获得所有可能的及格分数。

select sid, name, count(grade)
from student natural join exam 
group by sid, name
having count(distinct grade > 17) = 13; 



select sid, Name
from exam natural join student
group by sid
having count(distinct grade) = ( select count(distinct grade) 
                             from exam );

提前致谢!

你不应该使用 natural join。它使查询非常不清楚它在做什么。

无论如何,这段代码:

count(distinct grade > 17)

只能return0,或1,或2。为什么?因为它正在计算布尔表达式的不同值。而一个布尔表达式只有两个值(加上NULL)。

因此,它永远不会等于 13

有:

count(distinct grade > 17) 

你实际上是在计算布尔表达式 grade > 17 的不同值的数量,即 12,因为布尔表达式可能只有 2 个不同的值:0 false1 true.

你应该做的是在 grade > 17 时计算 grade 的不同值,这可以通过以下方式完成:

count(distinct case when grade > 17 then grade end)