【问题标题】:Dividing count on one table from another and grouping the results将一张表上的计数与另一张表相除并将结果分组
【发布时间】:2015-11-26 18:48:24
【问题描述】:

我正在尝试计算表 A 中的行与表 B 中的行的比率。如果我只需要计算整个集合的比率,这会很容易,但我想按存在的类别对它们进行分组在表 B 中。 表 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 命令在这里不起作用。

【问题讨论】:

    标签: sql postgresql count group-by divide


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      这应该返回你想要的:

      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 中的行数。

      【讨论】:

      • 似乎可以使用,但是 class_a 中不存在年龄,仅在 football_players 中存在..这仍然有效吗?
      • @Jam:您的查询在两个表中都显示age,但未指定表名。您能否添加有关这两个表、示例数据和预期结果的更多详细信息?
      • 是的,那是我的错误.. 否则我不知道该怎么做(请参阅我的表格和预期结果)
      【解决方案3】:

      这里是:DEMO

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

      【讨论】:

      • 嗯,我试图解决我的问题......情况不完全一样..?
      • 始终在答案中包含您的代码,指向外部网站的链接会关闭。尤其是 SQLFiddle 并不那么可靠。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多