我需要对每天的学生总数进行报告。我遇到的问题是,在我的子查询中,我不能做一个合适的小组,以便在白天我想知道有多少人因特定原因而进来。
我的查询是:
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虽然相同。
当我尝试在子查询中执行分组时,我收到此错误:
ERROR 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;
按照Evan的要求编辑1
我要查询的表只是会话表。我没有加入(正如你所注意到的)
该表格如下:
Primary Key : session_id
Foreign Key : anum(which is a student ID)
然后我们有:
why, aidyear, signintime, studentcomments, status
答案 0 :(得分:3)
您似乎应该可以使用CASE
与聚合:
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;