簡體   English   中英

計算SQL中每個組的總行數以及滿足特定條件的行數

[英]Counting total rows for each group in SQL and rows that meet certain condition

我有一個表,用於存儲有關員工和課程的信息:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM