题解 | #统计作答次数#

统计作答次数

http://www.nowcoder.com/practice/45a87639110841b6950ef6a12d20175f

一、明确需求

1. 题目要求:

统计出总作答次数total_pv、试卷已完成作答数complete_pv、已完成的试卷数complete_exam_cnt。

1. 需求解读

  • total_pv:计算作答记录数,数据有多少行,就由多少次
  • complete_pv:已完成作答数——提交记录submit_time is not null
  • complete_exam_cnt:已完成试卷数——提交记录submit_time is not null的exam_id数

二、解题思路

total_pv:count(1),count(*),count(col)都可以,col记得不能为有null的列

  • complete_pv:count(distinct submit_time)
  • complete_exam_cnt:用if或者case函数均可

三、代码展现

select count(distinct id) total_pv
    , count(distinct submit_time) complete_pv
    , count(distinct case when submit_time is not null then exam_id end) complete_exam_cnt
    # 或count(distinct if(submit_time is not null,exam_id,null) complete_exam_cnt
from exam_record

四、拓展

  1. IF(expr1,expr2,expr3):若expr1为True,返回expr2,反之返回expr3
  2. count(*),count(1),count(col)的区别
  • 1、count(*)和count(1)均是对数据列进行计数,功能相同,不同的仅在于计算效率方面不同
  • -2、count(col)计算col中not null的记录。
  • 具体推荐阅读:链接count(*) count(1)与count(col)的区别
全部评论

相关推荐

牛客ID:561366855:期望薪资多少?难以相信这简历找不到工作。说明二本电子信息专业想对口就业非常难。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务