小编典典

计算组内的百分比

sql

给出了用于以下命令的表:

select sex, count(*) from my_table group by sex;
select sex, employed, count(*) from my_table group by sex, employed;

给出:

  sex  | count 
-------+------
male   | 1960 
female | 1801

和:

 sex     | employed | count 
---------+----------+-------
 male    | f        |  1523 
 male    | t        |   437 
 female  | f        |  1491 
 female  | t        |   310

我在编写查询以计算每个性别组中受雇百分比时遇到困难。因此输出应如下所示:

 sex     | employed | count  | percent
---------+----------+--------+-----------
 male    | f        |  1523  | 77.7% (1523/1960)
 male    | t        |   437  | 22.3% (437/1960)
 female  | f        |  1491  | 82.8% (1491/1801)
 female  | t        |   310  | 17.2% (310/1801)

阅读 286

收藏
2021-03-17

共1个答案

小编典典

您可以通过子选择和联接来实现:

SELECT t1.sex, employed, count(*) AS `count`, count(*) / t2.total AS percent
  FROM my_table AS t1
  JOIN (
    SELECT sex, count(*) AS total 
      FROM my_table
      GROUP BY sex
  ) AS t2
  ON t1.sex = t2.sex
  GROUP BY t1.sex, employed;

我想不出其他办法。

2021-03-17