下面是学生表DDL和DML
CREATE TABLE STUDENTS
(
CLASS NUMBER,
STUDENT_ROLLNO NUMBER,
SUBJECT VARCHAR2(50)
);
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 1,'ENGLISH');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 1, 'MATHS');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 1, 'SCIENCE');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 1, 'ART');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 2, 'ENGLISH');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 2, 'MATHS');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 2, 'FRENCH');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 2, 'POETRY');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 3, 'ENGLISH');
INSERT INTO STUDENTS(CLASS, STUDENT_ROLLNO, SUBJECT) VALUES(1, 3, 'MATHS');
现在我需要找到该班的每个学生选择的共同科目。 对于这种情况,英语和数学将是结果。
我需要编写查询来获取所需的结果,因为它们是更多的类,结果应该是按类。
感谢。
答案 0 :(得分:2)
WITH SUB1 AS (
SELECT
CLASS,SUBJECT,COUNT(*) NMB FROM
STUDENTS
GROUP BY CLASS,SUBJECT
),SUB2 AS(
SELECT CLASS, MAX(NMB)MAX_NMB FROM
(SELECT
CLASS,COUNT(*) NMB FROM
STUDENTS
GROUP BY CLASS,SUBJECT
)
GROUP BY CLASS
)
SELECT SUB1.CLASS,SUB1.SUBJECT
FROM SUB1
INNER JOIN SUB2
ON SUB1.NMB=SUB2.MAX_NMB AND SUB1.CLASS=SUB2.CLASS
答案 1 :(得分:1)
没有任何自我加入:
SELECT class,
subject
FROM (
SELECT s.*,
COUNT( DISTINCT student_rollno ) OVER ( PARTITION BY class ) AS num_students
FROM students s
)
GROUP BY class, subject
HAVING COUNT( DISTINCT student_rollno ) = MAX( num_students );
<强>输出强>:
CLASS SUBJECT
----- -------
1 ENGLISH
1 MATHS