检索SQL列中特定值的百分位数

时间:2015-11-05 23:19:26

标签: mysql sql

让我们说我知道我在SQL列中有一个特定的值,我想确定它的百分位数。基于另一个SO帖子(https://dba.stackexchange.com/questions/13703/get-the-rank-of-a-user-in-a-score-table)我尝试修改它,它可以工作但返回列中每个值的等级:

mysql> SELECT FIND_IN_SET( sum_squares, (SELECT GROUP_CONCAT(sum_squares ORDER BY sum_squares DESC)                  |
    -> FROM entries)                                                                                                 |
    -> ) AS rank                                                                                                     |
    -> FROM entries;  

如下:

+------+                                                                                                             |
| rank |                                                                                                             |
+------+                                                                                                             |
|    4 |                                                                                                             |
|    4 |                                                                                                             |
|    2 |                                                                                                             |
|    3 |                                                                                                             |
|    1 |                                                                                                             |
+------+ 

我尝试通过在WHERE之前添加FROM entries语句来修改它,如下所示:

mysql> SELECT FIND_IN_SET( sum_squares, (SELECT GROUP_CONCAT(sum_squares ORDER BY sum_squares DESC)                  |
    -> FROM entries)                                                                                                 |
    -> ) AS rank          
    -> ) WHERE sum_squares = 5                                                                                             |
    -> FROM entries;  

这会导致以下错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE sum_squares = 5
FROM entries' at line 4

有人可以向我解释为什么我的查询似乎被禁止,如果还有其他方法可以做到这一点?我不想退回整个专栏!

这是一个示例entries表:

+----+-------------+
| id | sum_squares |
+----+-------------+
|  1 |           5 |
|  2 |           5 |
|  3 |          55 |
|  4 |          33 |
|  5 |         111 |
+----+-------------+

2 个答案:

答案 0 :(得分:0)

这是几乎在@ GordonLinoff的评论之后做了什么:

mysql> SELECT FIND_IN_SET( sum_squares, (SELECT GROUP_CONCAT( sum_squares ORDER BY sum_squares DESC)
    -> FROM entries HAVING sum_squares = 5)
    -> )  AS rank
    -> FROM entries

然而,这会返回匹配行中的答案以及其他行中的NULL,因此我欢迎对此进行改进。感谢。

+------+
| rank |
+------+
|    4 |
|    4 |
| NULL |
| NULL |
| NULL |
+------+

答案 1 :(得分:0)

如果您想要单个条目的排名,请尝试以下查询:

SELECT COUNT(DISTINCT sum_squares) + 1
FROM entries
WHERE sum_squares > 5 ;