mysql - 如何计算MySQL中的总数百分比

标签 mysql

我有以下问题:

select count(*) as headct
, case
when year(DOB) <= 1945 then 'Traditionalist'
when year(DOB) >= 1946 and year(DOB) < 1965 then 'Baby Boomer'
when year(DOB) >= 1965 and year(DOB) < 1981 then 'Gen X'
when year(DOB) >= 1981 then 'Gen Y'
end as generation
from ret_active
group by Generation with rollup;

它返回这个表:

headct    generation
--------------------------
1820      Baby Boomer
2208      Gen X
883       Gen Y
17        Traditionalist
4928      null

如何添加另一列来显示每个类别的总数百分比?换句话说,我怎样才能得到以下结果:

headct    generation      % of Total
-------------------------------------
1820      Baby Boomer     37%
2208      Gen Xm          45%
883       Gen Y           18%
17        Traditionalist  0%
4928      null            100%

谢谢!

最佳答案

select count(*) as headct
, case
    when year(DOB) <= 1945 then 'Traditionalist'
    when year(DOB) >= 1946 and year(DOB) < 1965 then 'Baby Boomer'
    when year(DOB) >= 1965 and year(DOB) < 1981 then 'Gen X'
    when year(DOB) >= 1981 then 'Gen Y'
  end as generation
, concat(round(count(*)/
    (select count(*) from ret_active)*100,0),'%') as '% of Total'
from ret_active
group by Generation with rollup

关于mysql - 如何计算MySQL中的总数百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22718691/

相关文章:

mysql - 在 Ubuntu 上纯粹从 bash 脚本安装 mysql 5.7

php - 忽略 MySQL Group By 值

php - MySQL 唯一键场景

mysql - 一般错误 : 1364 with STRICT_TRANS_TABLES disabled

mysql - 1305 - 程序 db.delete_catelog_item 不存在

c# - MVC5 SQL 左连接查询

mysql - 多个简单连接 Vs。多个简单选择

php - 从多个文件夹中批量插入图像(文件夹中包含图像)将不起作用

php - Phalcon 模型无法识别 AUTO_INCRMENT 表列

php - 带有外键数据的 laravel json 输出