sql多表查詢分組最大值

2021-08-03 10:43:37 字數 1636 閱讀 2286

問題描述:有三張表:學生表student(id,name),id為主鍵;課程表subject(id,name),id為主鍵;分數表score(studentid,subjectid,score),其中studentid與subjectid為聯合主鍵,一句sql語句查詢出:學號,姓名,課程名,課程最高分.

模擬實現如下:

三張表:

create table student

( id int primary key auto_increment,

`name` varchar(20)

)

create table subjects(

id int primary key auto_increment,

`name` varchar(20)

)

create table score(

studentid int references student(id),

subjectid int references subjects(id),

score int,

primary key(studentid,subjectid)

)

模擬插入的資料如下:

insert into student values(null,'zhangsan');

insert into student values(null,'lisi');

insert into subjects values(null,'chinese');

insert into subjects values(null,'english');

insert into score values(1,1,60);

insert into score values(1,2,90);

insert into score values(2,1,70);

insert into score values(2,2,80);

每個人解題都有自己的思路,我說一下我自己的思路:我認為難點在於要分組查詢出每個學科的最高分,所有要先對score表進行查詢,結果為每乙個subjectid對應乙個最高的score。首先,我想到的思路就是:得到相同學科的最高分數,再查詢score表,找到最高分數的記錄,**如下:

select * from score a where score=(select max(score) from score where subjectid=a.subjectid)
只要做到這,相信剩下的就沒有什麼難度了,就是簡單的多表查詢了,不多說了,直接上完整的**

select st.id,st.name,sj.name,sc.score from student st,subjects sj,

(select * from score a where score=(select max(score) from score where subjectid=a.subjectid)) sc

where st.id = sc.studentid and sj.id = sc.subjectid

快樂學習,快樂程式設計!

SQL分組最大值

employee表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1 joe 70000 1 2 henry 80000 2 3 sam 60000 2 4 max 90000 1 department...

SQL分組求最大值

訂單操作記錄表,需要獲取每個訂單最新的操作更新時間,以及操作id。使用 over 以及 row number 來實現 select from select operationid,orderno,updatetime,row number over partition by orderno orde...

sql 分組後的最大值

friday february 10,2006 03 29pm cst select customerid,max balance from temptable1 group by customerid 就可以達到目的了,我竟然半天不知道怎麼下手。看來是被上次max a,b 問題嚇怕了。msn 的這...