如何获得百分位数?

时间:2011-08-10 19:21:20

标签: mysql

我的表格中有3个字段,我可以按顺序排序(在其他一些字段中),我想创建一个单独的查询 - 进行某些分组后,等等。 - 给我所有的行,以及每个相对于这4个字段中每个字段的百分位数。

我该怎么做?我猜我需要一个子查询,但我不确定如何。


示例输入将是这样的:

age | first_name | last_name | votes
----+------------+-----------+-------
 10 | Bob        | Smith     |  2
 10 | Bob        | Smith     |  3
 50 | John       | Adams     |  1
 50 | John       | Adams     |  1
 50 | John       | Adams     |  2
100 | Andy       | Johnson   |  2

在进行一些转换后(例如,加起来投票),示例输出应该是这样的:

age | first_name | last_name | votes | age_per | first_name_per | last_name_per
----+------------+-----------+-------+---------+----------------+-------------
 10 | Bob        | Smith     |  5    |   33    |    66          |    99
 50 | John       | Adams     |  4    |   66    |    99          |    33
100 | Andy       | Johnson   |  2    |   99    |    33          |    66

2 个答案:

答案 0 :(得分:0)

这样的东西? (我现在没有MySQL实例来测试它)

SELECT age, 
       first_name, 
       last_name, 
       SUM(votes), 
       COUNT(age) / (SELECT COUNT(age) FROM table t WHERE t.age = age) as age_per, 
       COUNT(first_name) / (SELECT COUNT(first_name) FROM table t WHERE t.first_name = first_name) as first_name_per, 
       COUNT(last_name) / (SELECT COUNT(last_name) FROM table t WHERE t.last_name = last_name) as last_name_per
FROM table
GROUP BY age, first_name, last_name

答案 1 :(得分:0)

SELECT age
     , first_name 
     , last_name 
     , SUM(votes) AS votes
     , ( SELECT COUNT(DISTINCT age)
         FROM tableX AS a
         WHERE a.age <= t.age
       ) * 100 / distinct_age_count
       AS age_per
     , ( SELECT COUNT(DISTINCT first_name)
         FROM tableX AS f
         WHERE f.first_name <= t.first_name
       ) * 100 / distinct_first_name_count
       AS first_name_per
     , ( SELECT COUNT(DISTINCT last_name)
         FROM tableX AS l
         WHERE l.last_name <= t.last_name
       ) * 100 / distinct_last_name_count
       AS last_name_per
FROM
    tableX AS t
  CROSS JOIN
    ( SELECT COUNT(DISTINCT age) AS distinct_age_count
      FROM tableX
    ) AS ad
  CROSS JOIN
    ( SELECT COUNT(DISTINCT first_name) AS distinct_first_name_count
      FROM tableX
    ) AS fd
  CROSS JOIN
    ( SELECT COUNT(DISTINCT last_name) AS distinct_last_name_count
      FROM tableX
    ) AS ld
GROUP BY age
       , first_name
       , last_name