[英]SQL limit result to top 50%
我嘗試了兩種方法,但在mysql中失敗。
/*see top 50% students, but this sql can't work*/
select * from student_table order by chinese_score desc limit count(*) * 0.5 ;
/*also can't work*/
set @num= floor((select count(*) from test.student_score)*0.5);
select * from student_table order by chinese_score desc limit @num ;
如何在mysql中解決?
在Mysql中,可以使用用戶定義的變量在單個查詢中完成。
您可以在一個語句中將值存儲在用戶定義的變量中,稍后在另一條語句中引用它。 這使您可以將值從一個語句傳遞到另一個語句。
SELECT * FROM (
SELECT student_table.*, @counter := @counter +1 AS counter
FROM (SELECT @counter:=0) AS initvar, student_table
ORDER BY student_table.chinese_score DESC
) AS result
WHERE counter < (@counter/2) ORDER BY chinese_score DESC;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.