Showing Percentage on every row

88 Views Asked by At

I would like to show the percentage of gender on every row of the sql result. My data looks like:

 CREATE TABLE Results
 ( employeeId varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
 , Employee_Name varchar(228) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
 , gender varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
 , Citizenship varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 insert into Results values
 (1,'A','M','India'),
 (2,'B','F','India'),
 (4,'D','F','France'),
 (3,'C','F','Lebanon'),
 (5,'E','M','Sri Lanka');

The percentage by gender count would be M 40, F 60 by using

select gender, round(count(gender) * 100/sum(count(gender)) over (),2)  percentage 
  from Results 
 group 
    by gender;

This query will return the result for M & F but i would like the percentage to be repeated for every row in the table,

employeeId  EmployeeName    gender Citizenship    Percentage
        1           A          M        India          40 
        2           B          F        India          60
        4           D          F        France         60
        3           C          F        Lebanon        60
        5           E          M       Sri Lanka       40

How can i do this ?

dbfiddle

2

There are 2 best solutions below

0
forpas On BEST ANSWER

There is no need for group by or any joins.
Use COUNT() window function only:

select *, 
  round(100.0 * count(*) over (partition by gender) / count(*) over (), 2) percentage 
from Results 
order by employeeId

See the demo.
Results:

> employeeId | Employee_Name | gender | Citizenship | percentage
> :--------- | :------------ | :----- | :---------- | ---------:
> 1          | A             | M      | India       |      40.00
> 2          | B             | F      | India       |      60.00
> 3          | C             | F      | Lebanon     |      60.00
> 4          | D             | F      | France      |      60.00
> 5          | E             | M      | Sri Lanka   |      40.00
0
Tim Biegeleisen On

I would just join to a subquery which finds the percentage for each gender:

SELECT
    t1.employeeId,
    t1.EmployeeName,
    t1.gender,
    t1.Citizenship,
    t2.pct AS Percentage
FROM yourTable t1
INNER JOIN
(
    SELECT gender, ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS pct
    FROM yourTable
    GROUP BY gender
) t2
    ON t1.gender = t2.gender;

screen capture from demo link below

Demo