1

I tried two methods but failed in 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 ;

How to solve in mysql?

David דודו Markovitz
  • 35,505
  • 5
  • 55
  • 78
yichudu
  • 159
  • 2
  • 11

1 Answers1

2

In Mysql this can be done in a single query using user defined variables.

You can store a value in a user-defined variable in one statement and refer to it later in another statement. This enables you to pass values from one statement to another.

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;
dsharew
  • 9,927
  • 6
  • 43
  • 71