㈠ sql 語句查詢 前5名後5名的成績
不知道你的是什麼資料庫,我用oracle的寫法了。
兩種辦法:
分別求最大和最小,然後union all
select * from(select* from table order by 成績) where rownum<=5
union all
select * from(select* from table order by 成績 desc) where rownum<=5
利用排序,找到每個人的位置,然後輸出。排序的方法很多,可以用rownum排序,也可以用row_number()over()排序
我用row_number()over()寫一個
selecta.姓名,a.成績 from
(select row_number()over(order by 成績) num,姓名,成績 from table) a where a.num<=5 or
a.num>=(select count(*)-5 from table)
我沒實驗,不過就算有問題也應該不大。
sqlserver的版本是啥?是2005以上么?如果是
那麼利用那個row_number的應該也可以,不過為了讓分數一樣的人都出來,那麼最好改為
這種情況是假設前五齣現分數相同的話,假如前五名有六個人的情況,不過我沒有輸出名次,另外我上面的那種寫法也可以試試,sqlserver好像也可以。
不過如果你要是sql2005以前的版本那時sqlserver還沒有這幾個開窗函數,那就稍微有點麻煩了。
select姓名,成績 from
select rank()over(order by 成績) num,rank()over(order by 成績 desc) num_desc,姓名,成績 from table) a where a.num<=5 or a.num_desc<=5 order by 成績 desc
㈡ 用SQL命令查詢資料庫這門課排名前5的同學的學號和成績若成績相同按學號升序排列
sql server:
select top 5 學號,成績
from 成績表
where 課程名=『資料庫』
order by 成績 desc,學號
oracle :
select 學號,成績
from 成績表
where 課程名=『資料庫』and rownum<=5
order by 成績 desc,學號
㈢ 用SQL列出資料庫成績的前五名學生的學號、姓名、成績
select student.學號,姓名,成績 FROM STUDENT,SCORE WHERE STUDENT.學號=SCORE.學號 ORDER BY 成績 DESC TOP 5 (本語句適合二級)
㈣ 如何查詢資料庫中排名前幾位的數據
使用 select top 5 * from table order by id 時,報用select語句檢索oracle資料庫時出現ora-00923:未找到要求的from關鍵字。
因為該SQL語句是在SQLServer中的使版用的,如果權是在 Oracle中,需要使用 rownm 這個關鍵字用來返回 查詢的記錄條數。
eg: select * from table where rownnm<=5 order by id