2014-02-23 56 views
-2

我必須返回得分超過整體平均數的學生人數。如何從兩個以上的表中獲取數據?

這裏是我的兩個表:

CREATE TABLE student(Fields_ID INT, Name VARCHAR(20)); 
     INSERT INTO student(Fields_ID,Name) VALUES(30,'JYOTI'); 
     INSERT INTO student(Fields_ID,Name) VALUES(31,'KIRTI'); 
     INSERT INTO student(Fields_ID,Name) VALUES(32,'YOGITA'); 
     INSERT INTO student(Fields_ID,Name) VALUES(33,'RASHMI'); 
     INSERT INTO student(Fields_ID,Name) VALUES(34,'NUPUR'); 
SELECT * FROM student; 

CREATE TABLE Marks(Fields_ID INT, Student_ID INT NOT NULL,marks INT NOT NULL); 
     INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (30,40,100); 
     INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (31,41,88); 
     INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (32,42,72); 
     INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (33,43,33); 
     INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (34,44,15); 
SELECT * FROM Marks; 

這是我試圖返回我想要的輸出的代碼,但我無法形成正確的語法。

SELECT COUNT(student.name) 
From student INNER JOIN Marks 
    ON Marks.Fields_ID = student.Fields_ID 
HAVING marks>AVG(marks); 

我應該怎麼做呢?

+0

我相信'AVG()'和'COUNT()',你將需要'GROUP'。 – Shahar

+1

爲什麼你又問同樣的問題? http://stackoverflow.com/questions/21967954/how-to-fetch-data-from-three-or-more-tables –

+0

他們是不同的。在這個問題中,我必須找出只有得分的學生人數超過整體平均水平。 –

回答

1

試試這個方法:

SELECT COUNT(student.name) 
From student 
INNER JOIN Marks 
    ON Marks.Fields_ID = student.Fields_ID 
WHERE Marks.marks>(SELECT AVG(marks) 
        FROM marks); 

演示:http://sqlfiddle.com/#!2/0dd8ad/3

相關問題