多个表中多个COUNT SELECTS的总数不起作用

时间:2015-09-13 03:46:37

标签: sql count group-by

我有一份出勤报告,其中我希望像这样显示报告日:

enter image description here

我可以单独计算Sum,但不能计算所有Sum的总和

我的StudentAttendance表:

ID  ClassID SubjectID Day10 Day11   Day12   Day13   Day14   Day15         ProfessorID   
215     23    46                                        P                        36                                             36   
216     23    47                                        P                        36  
217     23    48                                        P                        36                                                   P                                                                     36   
218     17    35                                        P                        28

我试过这个查询:

select ClassID,
    sum(case when Day14= 'P' then 1 else 0 end) Present,
    sum(case when Day14= 'A' then 1 else 0 end) Absent,
    sum(case when Day14= 'L' then 1 else 0 end) Leave
from studentattendance 
group by ClassID,Day14

我尝试了Sum(Present.Absent,Leave)..但是没有工作我错过了什么?

1 个答案:

答案 0 :(得分:0)

SELECT没有带有多个FROM子句的SQL语法(WITHOUT嵌套)。 也许你想要这样的东西?

select 
  classID,
  count(Day14) Total,
  sum(case when Day14='P' then 1 else 0 end) Present,
  sum(case when Day14='A' then 1 else 0 end) Absent,
  sum(case when Day14='L' then 1 else 0 end) Leave   
from studentattendance
group by classID

此处Total仅是每个classID中的记录总数。 sum(case..when..)语句仅在满足特定条件时才模拟选择性count()Day14是存在,不存在或离开)。请注意,如果您希望列Total

中存在除此3之外的值,则无法保证Present+Absent+Leave等于Day14