Select TOP X (or bottom) percent for numeric values in MySQL

前端 未结 3 587
时光取名叫无心
时光取名叫无心 2020-11-29 10:15

I was wondering if there are any functions that can be used in MySQL to select the TOP X(or bottom) percent from a column containing numeric values.

Basically, I ha

3条回答
  •  甜味超标
    2020-11-29 10:43

    UPDATE: Much more thought-out explanation of the subject from much more knowing person here. Nonetheless, it still seems there's no embedded function in MySQL to calculate percentiles.

    Try:

    SELECT * FROM prices WHERE price >= (SELECT 0.9 * max(price) FROM prices)

    SELECT price FROM prices p1 WHERE
    (SELECT count(*) FROM prices p2 WHERE p2.price >= p1.price) <=
         (SELECT 0.1 * count(*) FROM prices)
    );
    

    This will give price P1 for which number of records in Price table having price >= P1 will be one tenth of total number of records in Price table. After that:

    SELECT * FROM prices WHERE price >= (SELECT price FROM prices p1 WHERE
    (SELECT count(*) FROM prices p2 WHERE p2.price >= p1.price) <=
         (SELECT 0.1 * count(*) FROM prices)
    );
    

    will return all desired records.

    Note: I didn't examine performance of this query, I think solution with temporary table/variable must be more effective.

提交回复
热议问题