sql - 计算 SQL 中每个组的总行数和满足特定条件的行数
问题描述
我有一张表,其中存储了有关员工和课程的信息:
Employee Course Attends
01 00001 yes
02 00001 no
03 00001 yes
04 00002 yes
05 00002 no
我想得到的是每门课程的注册人数和参加人数,以及每门课程的出席率。综上所述,我的查询结果是这样的:
Course Employees registered Employees with attendance Perc. attendance
00001 3 2 66
00002 2 1 50
我怎么能做到这一点?谢谢!
解决方案
您可以使用条件聚合来做到这一点:
select course, count(*) as num_registered,
sum(case when attends = 'yes' then 1 else 0 end) as num_attends,
avg(case when attends = 'yes' then 100.0 else 0 end) as percent_attends
from t
group by course;