在SQL

时间:2016-11-14 19:43:41

标签: sql oracle

我坚持查询并决定在这里寻求帮助。 我有2个表学生。在学生中,我有名称,在,我有成绩。

假设我们有3名学生

**X** 7,8,10
**Y** 6,9,7
**Z** 7 

如何选择等级为“7”的学生? 我试过了:

SELECT WHERE grade = 7 但考虑到有“7”但也有其他成绩的学生需要考虑。

我觉得这个问题很棘手,有人可以提一下吗?

4 个答案:

答案 0 :(得分:2)

一种方法是使用无条件和条件计数之间的比较:

select s.student_name
from   students s join grades g on s.student_id = g.student_id
group by student_id
having count(*) = count(case when g.value = 7 then 1 end)
;

(沿途猜测一些列名)

工作原理:加入两个表后,行按student_id分组。然后COUNT(*)计算所有等级,条件计数计算等于7的等级。当两个计数相等时(即所有等级为7),查询返回学生姓名。

另一种解决方案(效率较低):

select s.student_name 
from   students s inner join grades g on s.student_id = g.student_id
where  g.grade = 7
minus
select s.student_name
from   students s inner join grades g on s.student_id = g.student_id
where  g.grade != 7 or g.grade is null
;

答案 1 :(得分:1)

一种简单的方法是查看这样的任务:找到没有七年级以上成绩的学生。

select *
from students
where not exist
(
  select *
  from grades
  where grades.student_id = students.student_id
  and grades.grade <> 7
);

select *
from students
where student_id not in
(
  select student_id
  from grades
  where grade <> 7
);

答案 2 :(得分:0)

我认为INNER JOIN后跟独占LEFT JOIN就行了。像这样:

WITH

seven AS (
  SELECT a.id, a.name, b.grade
  FROM student_name a
  INNER JOIN student_grade b
  ON a.id = b.id
  WHERE b.grade = '7'
  )

, not_seven AS (
  SELECT a.id, a.name, a.grade
  FROM seven a
  LEFT JOIN student_grade
  ON a.id = b.id
  WHERE b.id IS NULL
  AND b.grade <> '7'
  )

SELECT * FROM not_seven;

答案 3 :(得分:0)

使用count和sum怎么样?那会有用吗?

   select s.student, Count(v.grade), sum(v.grade)
   From student as s 
        join values as v on v.student = s.student
   group by student
   having sum(v.grade) = 7 and count(v.grade) = 1