gpt4 book ai didi

mysql - 如何做这个sql查询?

转载 作者:可可西里 更新时间:2023-11-01 07:08:21 24 4
gpt4 key购买 nike

架构:

Student(studentid,name,age)
Course(coursename,dept)
enroll(studentid,coursename,grade)

我需要编写 sql 来查找每个年龄段的学生姓名,以及从历史和政治科学系选修的类(class)的最高分。

到目前为止我的尝试是

SELECT 
name
FROM
student
GROUP BY age
HAVING sid IN
(
SELECT
max(grade)
FROM
enroll e,enroll e1
WHERE
e.studentid = e1.studentid
AND e.coursename = (
SELECT coursename FROM course
WHERE
dname like '%History%'
)
AND e1.coursename = (
SELECT coursename FROM course
WHERE
dname like '%PoliticalScience%'
)
)

最佳答案

您可以使用子查询 获取最高分。试试看,

SELECT  d.*,
f.dept,
e.grade
FROM student d
INNER JOIN enroll e
on d.studentID = e.studentID
INNER JOIN course f
ON e.courseName = f.courseName
INNER JOIN
(
SELECT a.age, c.dept, Max(b.grade) maxGrade
FROM student a
INNER JOIN enroll b
on a.studentID = b.studentID
INNER JOIN course c
ON b.courseName = c.courseName
WHERE c.dept IN ('history','political science')
GROUP BY a.age, c.dept
) topScore
ON topscore.age = d.age AND
topscore.dept = f.dept AND
topscore.maxGrade = e.grade

关于mysql - 如何做这个sql查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com