【问题标题】:Counting total rows for each group in SQL and rows that meet certain condition计算 SQL 中每个组的总行数和满足特定条件的行数
【发布时间】:2019-07-01 10:54:55
【问题描述】:

我有一张存储员工和课程信息的表格:

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

我怎样才能做到这一点?谢谢!

【问题讨论】:

    标签: sql group-by where-clause


    【解决方案1】:

    您可以使用条件聚合来做到这一点:

    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;
    

    【讨论】:

    • 加一是取百分比的方式,多美啊。
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多