Calculating percentage within a group

后端 未结 2 805
离开以前
离开以前 2020-12-24 13:03

given a table that for the following commands:

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


        
相关标签:
2条回答
  • 2020-12-24 13:27

    You can do it with a sub-select and a join:

    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 off the top of my head.

    0 讨论(0)
  • 2020-12-24 13:48

    May be too late, but for upcoming searchers, possible solution could be:

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

    By IO Statistics this seems to be most effective solution - may be dependant on number of rows to be queried - tested on numbers above ...

    The same attitude could be used for getting male / female percentage:

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

    Regards, Jan

    0 讨论(0)
提交回复
热议问题