Calculation of interest within the group

for the table, for the following commands:

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

gives:

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

and

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

I’m having difficulty writing a query that calculates the percentage of employees in each sex group. Therefore, the output should look like this:

 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)
+5
source share
2 answers

You can do this with sub-selections and joins:

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;

I can’t think of other approaches from the head.

+6
source

It may be too late, but for future search engines, a possible solution might be:

select sex, employed, COUNT(*) / CAST( SUM(count(*)) over (partition by sex) as float)
  from my_table
 group by sex, employed

According to IO Statistics, this seems to be the most effective solution - it may depend on the number of rows that need to be requested - checked on the numbers above ...

The same ratio can be used to obtain the percentage of men and women:

select sex, COUNT(*) / CAST( SUM(count(*)) over () as float)
  from my_table
 group by sex

Regards, Yang

+8
source

All Articles