查询回答率最高的问题

正确答案1:
SELECT
question_id AS survey_log
FROM
surveyLog
GROUP BY
question_id
ORDER BY
count(CASE WHEN ACTION = 'answer' THEN 1 END )/ count(CASE WHEN ACTION = 'show' THEN 1 END)DESC,
question_id
LIMIT 1;
正确答案2:
SELECT
question_id AS survey_log
FROM
surveyLog
GROUP BY
question_id
ORDER BY
sum(ACTION = 'answer')/ sum(ACTION = 'show')DESC,
question_id
LIMIT 1;
count (表达式)--分组里非空记录数
count(*)--所有记录
count(1)--所有记录
count(case when job = 'CLERK' then 2 end )--CLERK 人数
count(comm)--有奖金的人数
count(distinct job)--distinct(去重),共有多少种工作
sum函数会忽略包含null字段的记录
正确答案3:
SELECT
question_id AS survey_log
FROM
surveyLog
GROUP BY
question_id
ORDER BY
count(ACTION = 'answer' OR NULL)/ count(ACTION = 'show' OR NULL)DESC,
question_id
LIMIT 1;
使用count()函数实现条件统计的基础是对于值为NULL的记录不计数,常用的有以下三种方式,假设统计num大于200的记录
select count(num > 200 or null) from a;
select count(if(num > 200, 1, null)) from a
select count(case when num > 200 then 1 end) from a
如count(release_year = '2006' or NULL) 这部分为什么要加上or NULL 直接count(release_year='2006')有什么问题吗?不就是要找release_year = '2006'的数据吗,为什么要计算NULL的数据?
答案:
因为当release_year不是 2006时,release_year='2006'结果是false不是NULL。
Count在值是NULL不统计数,count('任意内容')都会统计出所有记录数,因为count只有在遇见null时不计数,即count(null)=0,因此前者单引号内不管输入什么值都会统计出所有记录数,至于加上or NULL,很像其他编程里的or运算符,第一个表达式是true就是不执行or后面的表达式,第一个表达式是false 执行or后面的表达式。当release_year不为2006时release_year = '2006' or NULL的结果是NULL,Count才不会统计上这条记录数。
浙公网安备 33010602011771号