-1

次の 4 つのデータベース テーブルがあります。

学校

 School_ID,  School_Name

学生

Student_id, School_ID, Student Name

コース

Course_ID, Course_Name

Course_学生

Course_Id, Student ID

各生徒が少なくとも 3 つの科目に在籍している学校のリストを返すクエリを提案してください。

4

3 に答える 3

2

与えられたスキーマ

CREATE TABLE School
    (`School_ID` int, `School_Name` varchar(7))
;

INSERT INTO School
    (`School_ID`, `School_Name` )
VALUES
    (1, 'SchoolA'),
    (2, 'SchoolB'),
    (3, 'SchoolC')
;

CREATE TABLE Student
    (`Student_id` int, `School_ID` int, `Student_Name` varchar(4))
;

INSERT INTO Student
    (`Student_id`, `School_ID`, `Student_Name`)
VALUES
    (1, 1, 'John'),
    (2, 1, 'Alex'),
    (3, 2, 'Lex')
;

CREATE TABLE Course
    (`Course_ID` int, `Course_Name` varchar(9))
;

INSERT INTO Course
    (`Course_ID`, `Course_Name`)
VALUES
    (1, 'Math'),
    (2, 'Science'),
    (3, 'Chemistry'),
    (4, 'Physics'),
    (5, 'History')
;



CREATE TABLE Course_Student
    (`Course_ID` int, `Student_ID` int)
;

INSERT INTO Course_Student
    (`Course_ID`, `Student_ID`)
VALUES
    (1, 1),
    (2, 1),
    (3, 1),
    (1, 2),
    (1, 3),
    (2, 3),
    (4, 2),
    (5, 2)
;

上記のスキーマの予想される出力は、SchoolA少なくとも 3 つのコースに登録されているすべての学生がいる唯一の学校であるためです。

SELECT SCHOOL_ID, School_Name
FROM
(
    SELECT  d.SCHOOL_ID, e.School_Name,e.NoOfStudents
    FROM
        (
          SELECT  a.Student_ID, a.school_ID
          FROM    Student a
                  INNER JOIN Course_Student c
                      ON c.Student_ID = a.Student_ID
                  INNER JOIN Course d
                      ON c.Course_ID = d.Course_ID
          GROUP BY a.Student_ID, a.school_ID
          HAVING COUNT(*) >= 3
        ) d INNER JOIN
        (
          SELECT  b.School_ID, b.School_Name, COUNT(*) NoOfStudents
          FROM    Student a
                  INNER JOIN School b
                      ON a.School_ID = b.School_ID
          GROUP BY b.School_ID, b.School_Name
        ) e ON e.School_ID = d.School_ID
    GROUP BY d.SCHOOL_ID
    HAVING COUNT(*) = e.NoOfStudents
) s
于 2012-11-16T11:12:21.473 に答える
1
select School_name from School
where School_ID not in (
    select School_ID from Student 
    inner join Course_Student on Student.Student_id = Course_Student.[Student ID]
    group by Student_ID, School_ID, Course_Id
    having Count(Course_Id) < 3)
于 2012-11-16T11:31:54.627 に答える
0
Select School_Name, Student_Name, count(Course_Student.Course_ID) as total from School
inner join Student
on Course_Student.School_ID = Student.School_ID
inner join Course
on Student.Student_Id = Course.Student_Id
where total > 3
group by School_Name, Student_Name
于 2012-11-16T11:24:19.857 に答える