从2个表中的oracle db中的2个表中获取每个主题中带有标记的学生的前三名

时间:2017-08-15 12:39:21

标签: sql oracle

假设我有两个表:
1)名称和卷号的学生 2)带有卷号,主题和标记的表。

我希望获得输出,以便它会向我显示每个主题中排名前3位的学生。

可以使用的表格脚本是:

CREATE TABLE STUDENT ( ROLL_NO INT PRIMARY KEY, NAME VARCHAR(20));
INSERT INTO STUDENT VALUES (1,'NIKHIL');
INSERT INTO STUDENT VALUES (2,'VARUN');
INSERT INTO STUDENT VALUES (3,'NISHANT');
INSERT INTO STUDENT VALUES (4,'VISHAL');
INSERT INTO STUDENT VALUES (5,'GOURAV');
INSERT INTO STUDENT VALUES (6,'HEMANT');
INSERT INTO STUDENT VALUES (7,'SHUBHAM');
INSERT INTO STUDENT VALUES (8,'DHAWAN');
INSERT INTO STUDENT VALUES (9,'GAUTAM');


CREATE TABLE MARKS ( ROLL_NO INT, SUBJECT VARCHAR(20), MARKS INT);
INSERT INTO MARKS VALUES('1','MATHS','92');
INSERT INTO MARKS VALUES('1','SCIENCE','80');
INSERT INTO MARKS VALUES('1','ENGLISH','98');
INSERT INTO MARKS VALUES('1','HINDI','81');
INSERT INTO MARKS VALUES('2','MATHS','89');
INSERT INTO MARKS VALUES('2','SCIENCE','100');
INSERT INTO MARKS VALUES('2','ENGLISH','81');
INSERT INTO MARKS VALUES('2','HINDI','82');
INSERT INTO MARKS VALUES('3','MATHS','98');
INSERT INTO MARKS VALUES('3','SCIENCE','92');
INSERT INTO MARKS VALUES('3','ENGLISH','88');
INSERT INTO MARKS VALUES('3','HINDI','83');
INSERT INTO MARKS VALUES('4','MATHS','88');
INSERT INTO MARKS VALUES('4','SCIENCE','82');
INSERT INTO MARKS VALUES('4','ENGLISH','85');
INSERT INTO MARKS VALUES('4','HINDI','97');
INSERT INTO MARKS VALUES('5','MATHS','94');
INSERT INTO MARKS VALUES('5','SCIENCE','90');
INSERT INTO MARKS VALUES('5','ENGLISH','97');
INSERT INTO MARKS VALUES('5','HINDI','89');
INSERT INTO MARKS VALUES('6','MATHS','89');
INSERT INTO MARKS VALUES('6','SCIENCE','82');
INSERT INTO MARKS VALUES('6','ENGLISH','84');
INSERT INTO MARKS VALUES('6','HINDI','85');
INSERT INTO MARKS VALUES('7','MATHS','82');
INSERT INTO MARKS VALUES('7','SCIENCE','100');
INSERT INTO MARKS VALUES('7','ENGLISH','92');
INSERT INTO MARKS VALUES('7','HINDI','98');
INSERT INTO MARKS VALUES('8','MATHS','99');
INSERT INTO MARKS VALUES('8','SCIENCE','91');
INSERT INTO MARKS VALUES('8','ENGLISH','86');
INSERT INTO MARKS VALUES('8','HINDI','82');
INSERT INTO MARKS VALUES('9','MATHS','100');
INSERT INTO MARKS VALUES('9','SCIENCE','95');
INSERT INTO MARKS VALUES('9','ENGLISH','81');
INSERT INTO MARKS VALUES('9','HINDI','81');

Run It Here

提前感谢您的帮助 我需要在oracle上运行它

2 个答案:

答案 0 :(得分:1)

下面将加入表格并根据标记确定排名并通过主题对其进行分区

SELECT *
FROM
    (SELECT name,
        subject,
        marks,
        row_number() over (partition BY subject order by marks DESC) rank
    FROM student
    JOIN marks
    ON  student.roll_no = marks.roll_no
    )
WHERE rank <= 3

答案 1 :(得分:0)

[NSLocale appCurrent]