2

我需要生成一份关于每天学生总数的报告。我遇到的问题是,在我的子查询中,我无法进行适当的分组,以便在一天之内我想知道有多少人出于特定原因进入。

我的查询是:

SELECT 
     DATE_FORMAT(session.signintime, '%b %d %Y') Date, 
     COUNT(session.session_id) 'Total', 
     (SELECT COUNT(aidyear) FROM session WHERE aidyear = '12-13') '12-13',         
     (SELECT COUNT(aidyear) FROM session WHERE aidyear = '13-14') '13-14' 
FROM session 
WHERE status = '3' 
GROUP BY Date;

结果报告是:

+-------------+-------+-------+-------+
| Date        | Total | 12-13 | 13-14 |
+-------------+-------+-------+-------+
| Apr 15 2013 |    47 |    38 |    25 |
| Apr 16 2013 |     5 |    38 |    25 |
+-------------+-------+-------+-------+
2 rows in set (0.00 sec)

如您所见,2013 年 4 月 16 日总共只有 5 名学生。现在请注意,两行的 12-13 13-14 是相同的。

当我尝试在子查询中进行分组时,我收到此错误:

错误 1241 (21000):操作数应包含 1 列

意思是子查询返回超过一行到我的理解。

我试过这个查询:

SELECT 
      DATE_FORMAT(session.signintime, '%b %d %Y') Date, 
      COUNT(session.session_id) 'Total', 
      (SELECT DATE_FORMAT(session.signintime, '%b %d %Y') Date, 
      COUNT(aidyear) FROM session WHERE aidyear = '12-13' GROUP BY Date) '12-13',   
      (SELECT DATE_FORMAT(session.signintime, '%b %d %Y') Date, COUNT(aidyear) FROM session WHERE aidyear = '13-14' GROUP BY Date) '13-14' 
FROM session WHERE status = '3' 
GROUP BY Date;

编辑 1 根据 Evan 的要求

我查询的表只是会话表。我不加入(如你所见)

该表具有以下内容:

Primary Key : session_id
Foreign Key : anum(which is a student ID)

然后我们有: why, aidyear, signintime, studentcomments, status

4

1 回答 1

3

似乎您应该能够将 aCASE与聚合一起使用:

SELECT DATE_FORMAT(session.signintime, '%b %d %Y') Date, 
  COUNT(session.session_id) 'Total', 
  sum(case when aidyear = '12-13' then 1 else 0 end) '12-13',
  sum(case when aidyear = '13-14' then 1 else 0 end) '13-14'
FROM session 
WHERE status = '3' 
GROUP BY Date;
于 2013-04-16T13:38:29.093 回答