如何为这种情况编写sql查询?

时间:2015-10-30 08:04:11

标签: mysql sql

+-----+----------+------------+------------+
| id  | grade_id | student_id | subject_id |
+-----+----------+------------+------------+
| 249 |        1 |         27 |          1 |
| 250 |        1 |         27 |          2 |
| 251 |        1 |         27 |          4 |
| 252 |        1 |         28 |          1 |
| 253 |        1 |         28 |          2 |
| 254 |        1 |         28 |          4 |
| 255 |        1 |         29 |          1 |
| 256 |        2 |         29 |          2 |
| 257 |        3 |         29 |          4 |
+-----+----------+------------+------------+

我是sql查询的初学者。我需要上表中的student_id来为每个subject_id,grade_id应为1.而且我还需要所有subject_id的grade_id = 1的学生数。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,你希望那些1的学生适合所有科目:

SELECT student_id 
FROM Table
GROUP BY student_id
HAVING MAX(grade_id) = MIN(grade_id) -- only one grade
   AND MIN(grade_id) = 1

如果您的成绩仅为>= 1

SELECT student_id 
FROM Table
GROUP BY student_id
HAVING MAX(grade_id) = 1   -- no grade greater than 1

为了计算,您只需将此查询嵌套在派生表中:

SELECT COUNT(*)
FROM
 (
   SELECT student_id 
   FROM Table
   GROUP BY student_id
   HAVING MAX(grade_id) = MIN(grade_id) -- only one grade
      AND MIN(grade_id) = 1
 ) AS dt

答案 1 :(得分:0)

使用NOT EXISTS返回没有其他grade_id而不是1的学生:

 select distinct student_id
 from tablename t1
 where not exists (select 1 from tablename t2
                   where t2.student_id = t1.student_id
                     and t2.grade_id <> 1)

SELECT DISTINCT只给每位学生一次。)

要计算这些学生,请使用派生表:

select count(*)
from
(
 select distinct student_id
 from tablename t1
 where not exists (select 1 from tablename t2
                   where t2.student_id = t1.student_id
                     and t2.grade_id <> 1)
)

答案 2 :(得分:-1)

您的第一个查询要求不是很清楚,请详细说明。

对于第二个(如果我理解正确的话):

SELECT subject_id, COUNT(student_id) 
FROM Table WHERE grade_id = 1 
GROUP BY subject_id