COUNT()、DISTINCT、IF()
SQL124 统计作答次数
解答:
select count(exam_id) as total_pv,
count(submit_time) as complete_pv,
count(DISTINCT if(submit_time is not null, exam_id, null)) as complete_exam_cnt
from exam_record;
收获:
- count()聚合函数不会统计value为null的的值。
- DISTINCT也是一样,null不会当作一条记录
- if() 函数 判断第一个参数表达式,如果为true那么返回第二个参数,否则返回第三个参数。
USING()
SQL125 得分不小于平均分的最低分
解答:
select min(score) as min_score_over_avg
from exam_record join examination_info using(exam_id)
where tag ='SQL' and score>=
(select avg(score) from exam_record join examination_info using(exam_id) where tag='SQL')
收获:using函数在关联查询中可以起到相当于on的作用,两个表的关联字段名要相同,比如 student.id = score.id 可以换成using(id)。
<>、<=>、is
SQL10 用where过滤空值练习
解答:过滤空值的三种方法:
(1) Where 列名 is not null
(2) Where 列名 != 'null'
(3) Where 列名 <> 'null'
收获:我们在使用is not null 时,null不加引号,用!=和<>要加引号。 <=>相当于is 和 = 的结合,= 不能用来判断为null的is不能用来直接判断某个值,刚好<=>解决了这两个弊端。
round()、group by()
SQL18 分组计算练习题
解答:
select gender,university,count(*) user_num,
round(avg(active_days_within_30),1) avg_active_day,
round(avg(question_cnt),1) avg_question_cnt from user_profile
group by gender,university
收获:
round(x,d) : 四舍五入x,保留d位
round(x) :四舍五入x,保留0位
round(x,-d) : 四舍五入x,x的后d位为0,保留0位
group by x,y : 只有x和y都相同才分为一组
sql执行顺序
SQL19 分组过滤练习题
解答:
select university, round(avg(question_cnt),3) avg_question_cnt, round(avg(answer_cnt),3) avg_answer_cnt from user_profile
group by university
having avg_question_cnt < 5 or avg_answer_cnt < 20;
收获:在where中不能使用select中的别名,也不能使用聚合函,但是有例外,having中可以使用别名
sql执行的顺序:
(1) FROM (2) ON (3) JOIN (4) WHERE (5) GROUP BY (6) 聚合计算 (7) WITH {CUBE|ROLLUP} (8) HAVING (9) SELECT (10) DISTINCT (11) ORDER BY (12) LIMIT