Search code examples
sqlpostgresqlcountgroup-bydivide

Dividing count on one table from another and grouping the results


I am trying to calculate the ratio of rows in table A to rows in table B. This would have been easy if I only had to calculate the ratio for the whole sets, but I want to group them by a category that exists in table B. Table A and B are linked through a primary key (id).

Edit:

I tried the following:

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)

but the group by command does not work here.


Solution

  • You need an outer join, then divide count of the rows in the outer joined tables by the total number of rows in the group:

    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  
    

    The cast ::numeric is necessary to get fractional values, otherwise the result of the division will be converted to an integer.

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