如何发出一个请求,列出表格中前三名的名称和等级
答案 0 :(得分:2)
在SQL Server中:
SELECT TOP 3 G.student_id, S.name, S.sex, G.grade
FROM Grades G
INNER JOIN Student S
ON G.student_id = S.student_id
WHERE S.sex = 'm'
ORDER BY grade DESC
答案 1 :(得分:1)
如果您的数据库是Oracle,请使用:
select name, grade
from
(
select s.name, g.grade, dense_rank() over (order by grade desc) dr
from students s join grades g on ( s.student_id = g.student_id )
where s.sex = 'm'
)
where dr <= 3;
如果DB是Mysql或PostgreSQL,则使用:
select s.name, g.grade
from students s join grades g on ( s.student_id = g.student_id )
where s.sex = 'm'
order by g.grade desc
limit 3;
答案 2 :(得分:1)
您可以使用rownum来获取此结果。
如果需要,您可以尝试下面的一个并进行调整。
选择* from(SELECT st.name,gr.grade FROM students st,grade gr 其中st.student_id = gr.student_id和st.sex ='m'的顺序 等级DESC)在哪里 rownum&lt; = 3;
答案 3 :(得分:1)
SELECT name, grade
FROM students
JOIN grades USING(student_id)
WHERE sex = 'm'
ORDER BY grade desc
LIMIT 3
JOIN
表格WHERE
ORDER BY..desc
按降序排序(按等级排序),以便更大的数字位于顶部LIMIT
SELECT TOP 3 s.name, g.grade
FROM students s
JOIN grades g ON ( s.student_id = g.student_id )
WHERE sex = 'm'
ORDER BY grade desc
JOIN
表格WHERE
ORDER BY..desc
按降序排序(按等级排序),以便更大的数字位于顶部TOP
注意:您可能希望在结果中包含唯一ID,因为您可能有许多同名学生,结果不明确
答案 4 :(得分:0)
这个问题听起来像来自学生做作业!无论如何,下面的一些Oracle SQL可能会有所帮助。
SELECT STUDENT_NAME, STUDENT_GRADE
FROM (
SELECT S.NAME AS "STUDENT_NAME", G.GRADE AS "STUDENT_GRADE"
FROM STUDENTS S JOIN GRADES G USING (STUDENT_ID)
WHERE S.SEX='m'
ORDER BY 2
)
WHERE ROWNUM < 4;
Oracle更高版本:
SELECT S.NAME AS "STUDENT_NAME", G.GRADE AS "STUDENT_GRADE"
FROM STUDENTS S JOIN GRADES G USING (STUDENT_ID)
WHERE S.SEX='m'
ORDER BY 2
FETCH FIRST 3 ROWS ONLY;