题解 | #大小写混乱时的筛选统计#
大小写混乱时的筛选统计
http://www.nowcoder.com/practice/81cb12931a604811ae69d332515c7734
思路是把试卷作答数小于3的信息表t1和完整的信息表t2做连接。
SELECT t1.tag, t2.answer_cnt FROM
(SELECT exam_record.exam_id, tag, COUNT(start_time) answer_cnt
FROM examination_info,exam_record
WHERE examination_info.exam_id=exam_record.exam_id
GROUP BY exam_record.exam_id,tag
HAVING answer_cnt<3) t1
JOIN
(SELECT exam_record.exam_id, tag, COUNT(start_time) answer_cnt
FROM examination_info,exam_record
WHERE examination_info.exam_id=exam_record.exam_id
GROUP BY exam_record.exam_id,tag) t2
ON UPPER(t1.tag)= t2.tag AND t1.tag != t2.tag;
但是上面的代码运行结果有误,dont know why。
下面的代码可以得到正确答案。下面的代码去掉了SELECT exam_record.exam_id和GROUP BY exam_record.exam_id。但是按照题目的意思难道不是按照exam_id,tag分组得到用每张试卷的作答数吗?最令我疑惑的是,就本题的数据而言,上面做法得到的t1,t2表和下面做法得到的t1,t2表在tag分类计数方面是一样的结果的呀。但是上面的代码就是不对。
SELECT t1.tag, t2.answer_cnt FROM
(SELECT tag, COUNT(start_time) answer_cnt
FROM examination_info,exam_record
WHERE examination_info.exam_id=exam_record.exam_id
GROUP BY tag
HAVING answer_cnt<3) t1
JOIN
(SELECT tag, COUNT(start_time) answer_cnt
FROM examination_info,exam_record
WHERE examination_info.exam_id=exam_record.exam_id
GROUP BY tag) t2
ON UPPER(t1.tag)= t2.tag AND t1.tag != t2.tag;
第二点要说的,按理说用UPPER(t1.tag)= t2.tag内连接后,不会出现c++和c++,sql和sql连接在一起的情况(因为UPPER(c++)不等于c++呀),但事实是连接后会出现c++和c++,sql和sql连接的情况。所以要追加条件t1.tag != t2.tag。
第三点要说的,平台是不是有bug。讨论区的下面做法,在平台上通过了。但是在SQL server会报错:“选择列表中的列 'exam_record.exam_id' 无效,因为该列没有包含在聚合函数或 GROUP BY 子句中。” 我也是一样的观点。