Home > OS >  How to calculate percentages in a group using SQL
How to calculate percentages in a group using SQL

Time:02-22

Suppose I have a table employee

(ID, status, department)

Suppose the status can only be 'f' or 'c'.

How to calculate the % of f's and c's in each department?

Update: the four fields in the output should be

A. DEPTNAME B. F_PCT C. C_PCT D. EMPCOUNT in that Dept

CodePudding user response:

You can use a window function to accomplish that:

select department, status,
(count(status) / sum(count(status)) over (partition by department)) * 100.0 as percentage
from employee
group by department, status
  •  Tags:  
  • sql
  • Related