gpt4 book ai didi

sql - 计算组内的百分比

转载 作者:行者123 更新时间:2023-12-03 12:06:27 24 4
gpt4 key购买 nike

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

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)

最佳答案

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

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;

我想不出其他办法。

关于sql - 计算组内的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1823599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com