如何获取MySQL中不同行的数量?

时间:2013-09-24 07:46:24

标签: mysql sql count

我使用了以下查询:

select tblclass.classname,tblattendance.id 
 from tblclass,tblattendance
where tblclass.classcode=tblattendance.classcode 
  and tblattendance.attdate='2013-07-01'

此查询的输出如下:

enter image description here

现在我想要的不是上面的结果,我想要像IB-2,IC-5这样的不同类别。 请告诉我在查询中需要进行哪些修改才能获得所需的结果

3 个答案:

答案 0 :(得分:3)

使用Group By SQL子句并添加聚合函数Count

select tblclass.classname, Count(tblattendance.id) as counter 
from tblclass,tblattendance 
where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01'
group by tblclass.classname

答案 1 :(得分:0)

试试这个

select count(tblattendance.id),tblclass.classname from tblclass,tblattendance 
where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01' 
group by tblclass.classname

答案 2 :(得分:0)

COUNT()使用GROUP BY功能。也可以使用JOIN

SELECT tc.classname, COUNT(tc.classname) AS COUNTS
  FROM tblclass tc 
  JOIN tblattendance tt
    ON tc.classcode = tt.classcode
 WHERE tt.attdate='2013-07-01'
 GROUP BY tc.classname