MySQL计数记录的频率

时间:2012-06-13 10:28:35

标签: mysql sql

表:

laterecords
-----------
studentid - varchar
latetime - datetime
reason - varchar

students
--------
studentid - varchar -- Primary
class - varchar

我想进行查询以显示以下内容:

Sample Report

Class      No of Students late  1 times  2 times   3 times  4 times    5 & more 
Class A        3                  1       0         2         0         0
Class B        1                  0       1         0         0         0

我的查询可以显示第一列结果:

SELECT count(Distinct studentid), class FROM laterecords, students
WHERE students.studenid=laterecords.studentid AND
GROUP BY class

我只能想到获取每列的结果并将它们存储到php数组中。然后用HTML回显它们。

有没有更好的SQL方法来执行上述操作?如何处理mysql查询?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
    a.class,
    COUNT(b.studentid) AS 'No of Students late',
    SUM(b.onetime) AS '1 times',
    SUM(b.twotime) AS '2 times',
    SUM(b.threetime) AS '3 times',
    SUM(b.fourtime) AS '4 times',
    SUM(b.fiveormore) AS '5 & more'
FROM
    students a
LEFT JOIN
    (
        SELECT
            aa.studentid,
            IF(COUNT(*) = 1, 1, 0) AS onetime,
            IF(COUNT(*) = 2, 1, 0) AS twotime,
            IF(COUNT(*) = 3, 1, 0) AS threetime,
            IF(COUNT(*) = 4, 1, 0) AS fourtime,
            IF(COUNT(*) >= 5, 1, 0) AS fiveormore
        FROM 
            students aa
        INNER JOIN
            laterecords bb ON aa.studentid = bb.studentid
        GROUP BY 
            aa.studentid
    ) b ON a.studentid = b.studentid
GROUP BY
    a.class

答案 1 :(得分:0)

怎么样:

SELECT numlates, `class`, count(numlates)
FROM
  (SELECT count(laterecords.studentid) AS numlates, `class`, laterecords.studentid
   FROM laterecords,
        students
   WHERE students.studentid=laterecords.studentid
   GROUP BY laterecords.studentid, `class`) aliastbl
GROUP BY `class`, numlates