Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: LIMIT by a percentage of the amount of records?

Tags:

sql

mysql

Let's say I have a list of values, like this:

id  value
----------
A   53
B   23
C   12
D   72
E   21
F   16
..

I need the top 10 percent of this list - I tried:

  SELECT id, value 
    FROM list
ORDER BY value DESC
   LIMIT COUNT(*) / 10

But this doesn't work. The problem is that I don't know the amount of records before I do the query. Any idea's?

like image 355
Dylan Avatar asked Apr 10 '11 22:04

Dylan


1 Answers

Best answer I found:

SELECT*
FROM    (
    SELECT list.*, @counter := @counter +1 AS counter
    FROM (select @counter:=0) AS initvar, list
    ORDER BY value DESC   
) AS X
where counter <= (10/100 * @counter);
ORDER BY value DESC

Change the 10 to get a different percentage.

like image 94
Dylan Avatar answered Sep 22 '22 21:09

Dylan