题解|含UNION排序|#每个题目每份试卷作答的人数和次数#

每个题目和每份试卷被作答的人数和次数

https://www.nowcoder.com/practice/203d0aed8928429a8978185d9a03babc

(SELECT exam_id AS tid, COUNT(DISTINCT(uid)) AS uv, COUNT(uid) AS pv
FROM exam_record 
GROUP BY tid)
UNION ALL
(SELECT question_id AS tid, COUNT(DISTINCT(uid)) AS uv, COUNT(uid) AS pv
FROM practice_record 
GROUP BY tid)
ORDER BY left(tid,1) DESC, uv DESC, pv DESC

注意UNION 和ORDER BY同时存在时的用法

法一:

SELECT * FROM
(SELECT exam_id AS tid, COUNT(DISTINCT exam_record.uid) uv,
COUNT(*) pv FROM exam_record 
GROUP BY exam_id
ORDER BY uv DESC, pv DESC) t1

UNION 

SELECT * FROM
(SELECT question_id AS tid, COUNT(DISTINCT practice_record.uid) uv,
COUNT(*) pv FROM practice_record 
GROUP BY question_id
ORDER BY uv DESC, pv DESC) t2;

知识点是UNION后的排序问题,ORDER BY子句只能在最后一次使用。 如果想要在UNION之前分别单独排序,那么需要这样:

SELECT * FROM
( SELECT * FROM t1  ORDER BY 字段 ) newt1 ## 一定要对表重新命名,否则报错 
UNION
SELECT * FROM
( SELECT * FROM t2  ORDER BY 字段 ) newt2

法二:用tid字段的左边第一个数来排序。

SELECT exam_id AS tid, COUNT(DISTINCT exam_record.uid) uv,
COUNT(*) pv FROM exam_record 
GROUP BY exam_id

UNION 

SELECT question_id AS tid, COUNT(DISTINCT practice_record.uid) uv,
COUNT(*) pv FROM practice_record 
GROUP BY question_id
 
ORDER BY LEFT(tid,1) DESC, uv DESC, pv DESC;

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-24 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
粗心的雪碧不放弃:纯学历问题,我这几个月也是一直优化自己的简历,后来发现优化到我自己都觉得牛逼的时候,发现面试数量也没有提升,真就纯学历问题
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务