MYSQL捆绑最大化

时间:2012-11-27 19:41:37

标签: mysql subquery

您好我有一张桌子列出西班牙语课程的开始和结束时间以及日期和老师。 我正在尝试编写一个MYSQL查询,列出每个教师拥有最多课程的日期,即他们最繁忙的那一天。 如果有几天我想要展示两者。

这是我到目前为止所得到的但它只返回一个日期,即使有一个平局,我觉得这是因为我最后在老师的分组

SELECT teacher_no, date
FROM (
   SELECT COUNT(date)AS counted,teacher_no,date
   FROM Spanish
   GROUP BY teacher_no,date
) AS t
GROUP BY teacher_no

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT  teacher_no, date, COUNT(date) AS counted
FROM    Spanish s
GROUP BY teacher_no, date
HAVING  COUNT(date) = (SELECT COUNT(date) AS counted
                       FROM Spanish
                       WHERE teacher_no = s.teacher_no
                       GROUP BY teacher_no, date
                       ORDER BY counted DESC
                       LIMIT 1
                      );

答案 1 :(得分:0)

我不确定为什么要在内部查询中计算日期。我认为计算开始时间更有意义。这将为您提供每个教师在每个日期的课程数量表:

SELECT COUNT(start_time) AS classes, teacher_no, date
FROM Spanish
GROUP BY tearcher_no, date) AS t

对于特定的teacher_no X,您可以按课程数量排序,以获得最多课程的日期:

SELECT date
FROM (        
    SELECT COUNT(start_time) AS classes, date
    FROM Spanish
    GROUP BY date
    WHERE teacher_no = X) AS t
ORDER BY classes DESC
LIMIT 1

最后,您可以通过

获取所有教师的列表
SELECT
    a.teacher_no,
    (SELECT date
     FROM
         (SELECT COUNT(b.start_time) AS classes, b.date
          FROM Spanish AS b
          GROUP BY b.date
          WHERE a.teacher_no = b.teacher_no) AS t
     ORDER BY classes DESC
     LIMIT 1) AS date
FROM Spanish AS a
GROUP BY a.teacher_no