将一个 table 的计数与另一个计数相除并对结果进行分组

Dividing count on one table from another and grouping the results

我正在尝试计算 table A 中的行与 table B 中的行的比率。如果我只需要计算整个集合的比率,这会很容易,但是我想按 table B 中存在的类别对它们进行分组。 Table A 和 B 通过主键 (id) 链接。

编辑:

我尝试了以下方法:

select
    (select count(*) from class_a a left join football_players b on (b.id = a.id) group by age)
    /
    (select count(*) from football_players group by age)

但是group by 命令在这里不起作用

这里是:DEMO

select age,
(1-(select count(*) from tableA a where a.id=b.id)/count(*) )*100
from tableB b
group by age

这应该return你想要的:

SELECT p.age, 100 * COUNT(c.id) / COUNT(p.id)
FROM football_players AS p
LEFT JOIN class AS c
  ON p.id = c.id
GROUP BY p.age

class_a 中的行数除以 football_players 中的行数。

您需要外连接,然后将外连接表中的行数除以组中的总行数:

select fp.age, 
       (count(cl.id)::numeric / count(*)::numeric) * 100 as ration,
       count(cl.id) as class_count, 
       count(*) as age_count
from football_players fp
  left join class cl on fp.id = cl.id
group by fp.age  

获取小数值需要强制转换::numeric,否则除法结果将被转换为整数。

SQLFiddle: http://sqlfiddle.com/#!15/3373c/3