2

テーブル:

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クエリを実行する方法は?

4

2 に答える 2

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
于 2012-06-13T11:32:56.680 に答える
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
于 2012-06-13T10:54:23.687 に答える