两个COUNT和一个GROUP BY

时间:2013-11-21 18:30:07

标签: mysql sql symfony doctrine-orm

我坚持这个查询,我想帮忙。

所以我有两张桌子:课程和缺席。

我的询问的目的是为学生计算一年中每个月的所有课程和缺席。

只有课程,我有这个问题:

SELECT DATE_FORMAT(c.date, "%M") AS month,
       COUNT(*) AS courses
FROM Course c
GROUP BY month
ORDER BY MONTH(c.date);

结果如下:

+-----------+--------+
| month     | courses|
+-----------+--------+
| January   |     24 |
| February  |     20 |
| March     |     20 |
| April     |     22 |
| May       |     23 |
| June      |     20 |
| July      |     23 |
| August    |     22 |
| September |     20 |
| October   |     23 |
| November  |     23 |
| December  |     21 |
+-----------+--------+

我希望有一个新专栏,就像课程一样,但缺席。

我的缺席列是:id,user_id, course_id ,原因,对齐

那么,是否可以使用课程组和缺勤计数?

如果是,怎么样?

提前致谢,

编辑:

我现在有了这个问题:

SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
             COUNT(*) AS courses
      FROM Course c
      GROUP BY month) a
INNER JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
                   COUNT(*) AS absences
            FROM Absence a
            LEFT JOIN Course c
            ON a.course_id = c.id
            GROUP BY month) b
ON a.month = b.month;

结果是:

+----------+---------+----------+
| month    | courses | absences |
+----------+---------+----------+
| November |      23 |        2 |
| October  |      23 |        1 |
+----------+---------+----------+

数字很好,但是当没有缺席时,课程不会显示。 有没有办法在缺席时得到0?

编辑2:

这是有效的查询:

SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
             COUNT(*) AS courses
      FROM Course c
      GROUP BY month) a
LEFT JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
                   COUNT(*) AS absences
            FROM Absence a
            LEFT JOIN Course c
            ON a.course_id = c.id
            GROUP BY month) b
ON a.month = b.month;

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
             COUNT(*) AS courses
      FROM Course c
      GROUP BY month) a
LEFT JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
                   COUNT(*) AS absences
            FROM Absence a
            LEFT JOIN Course c
            ON a.course_id = c.id
            GROUP BY month) b
ON a.month = b.month;

这有两个子查询,一个用于查找课程计数,另一个用于缺勤。然后你按月加入他们。

它应该能满足您的需求。

答案 1 :(得分:0)

您应该可以使用内联视图执行此操作:

SELECT c.month, c.courses, a.absences
FROM  (
        SELECT DATE_FORMAT(date, "%M") AS month,
               COUNT(*) AS courses
        FROM Course
        GROUP BY month
      ) AS c
      JOIN  (
              SELECT DATE_FORMAT(date, "%M") AS month,
                     COUNT(*) AS absences
              FROM Absence
              GROUP BY month
            ) AS a
        ON a.month = c.month
ORDER BY c.month