获取mysql中某个值的出现百分比

时间:2014-03-17 14:09:45

标签: mysql sql

我想获得某个版本的百分比。如果将信息存储在mytable

ID | name | version
===================
 1 | foo  | 1.0
 2 | bar  | 1.0
 3 | loo  | 1.1
 4 | zoo  | 1.2

我想得到这个结果

version | percentage
====================
 1.0    | 0.500
 1.1    | 0.250
 1.2    | 0.250

我的陈述目前(没有百分比)

SELECT a.version, FROM mytable AS a GROUP BY version ORDER BY version ASC

3 个答案:

答案 0 :(得分:3)

此查询应该有效:

select version, count(*) / const.cnt
from mytable cross join
     (select count(*) as cnt from mytable) const
group by version
order by version;

答案 1 :(得分:1)

使用COUNT

SELECT version, COUNT(version)/(SELECT COUNT(*) FROM table)
FROM table
GROUP BY version

答案 2 :(得分:1)

SELECT a.version, count(*)/full.full_count as percentage
FROM mytable AS a,
     (SELECT count(*) as full_count  FROM mytable) as full
GROUP BY version 
ORDER BY version ASC