WHERE条件不适用于聚合函数

时间:2015-05-16 07:08:35

标签: mysql

我正在尝试使用以下查询从表中选择数据。

我的桌子: enter image description here

SELECT COUNT(*) AS totalcount,
       SUM(English) as EnglishTotal,
       SUM(Tamil) as TamilTotal,
       SUM(Maths) as MathsTotal,
       SUM(EVS) as EVSTotal,
       SUM(Science) as ScienceTotal 
  from StudentMarks 
 where Class='"+Classs+"' and Section='"+Section+"' and ExamType='"+Exam+"';

如果我使用下面的ResultSet检查上述查询,

if(!rscount.isBeforeFirst()){   
    System.out.println("Cominggggg iffff");
}
else{
    System.out.println("Cominggggg elsee");
}

条件总是转到其他部分甚至WHERE条件不满足。

注意:如果我将查询更改为SELECT * from StudentMarks where Class='"+Classs+"' and Section='"+Section+"' and ExamType='"+Exam+"';,那么它的工作正常。

有人可以指导我在哪里做错了吗?

1 个答案:

答案 0 :(得分:3)

请尝试以下查询。

SELECT COUNT(*) AS totalcount,SUM(English) as EnglishTotal,
SUM(Tamil) as TamilTotal,SUM(Maths) as MathsTotal,
SUM(EVS) as EVSTotal,SUM(Science) as ScienceTotal 
from StudentMarks where Class='"+Classs+"' 
and Section='"+Section+"' and ExamType='"+Exam+"' GROUP BY Section;

我在条件之后添加了group by子句。