SQL常见雷区,函数,优化,执行顺序,使用技巧汇总
一、sql使用技巧
1、去重统计
select count(distinct 去重字段) from 表
2、字段别名和 group by
踩这个坑还是很难受的,亏得公司的学长看出来了,希望下次不要再入坑了。
sql1:
select d.cellid,d.num from(
select z.cellid,avg(z.rsrp) as num
from data_zlwc z
where z.cellid!=''
group by z.cellid)
d where d.num=-60 ;
sql2:
select cellid,avg (rsrp) as rsrp
from yrh.data_zlwc
where cellid!=''
and rsrp =-60
group by cell
说一下具体的区别和注意事项:
1、sal1查的是avg(rsrp)=-60,sql2查的是rsrp=-60;
2、如果需要给字段取别名,不要将新取的别名和原有的字段名重复,
这样会导致所查询的字段是在结果上做的筛选,而不是在原数据上的筛选;
3、group by的语法,不能对结果进行筛选,
group by子句必须在where子句之后,order by子句之前。
Tips:
where 和 having:
1、聚合函数:例如SUM, COUNT, MAX, AVG等。这些函数和其它函数的根本区别就是它们一般作用在多条记录上;
2、having是分组(group by)后的筛选条件,分组后的数据组内再筛选;
3、where子句中不能使用聚集函数,而having子句中可以,所以在集合函数中加上了hiving来起到测试查询结果是否符合条件的作用。即having子句的适用场景是可以使用聚合函数;
4、having 子句限制的是组,而不是行。having 子句中的每一个元素也必须出现在select列表中。有些数据库例外,如oracle。
3、join
与join相关的查询后会出现2个相同名的字段,这时候需要在查询的时候指定具体表名。
--left join 中on/and 对左表中字段做条件限制无意义,左表中所有数据依旧会被查出来,左表中的字段筛选必须在where中增加条件;对右表中字段做条件限制会对右表数据先做筛选再连接,结果不显示;
--join 中on/and 对两边表中的字段做限制都会起作用。
select *
from sc s
left join student t on s.sid = t.sid
where s.cid = (select cid from teacher t
left join course c on t.tid = c.tid where t.tname = '张三');
4、行列转换
case xox when ooxx then xoxo end xxoo
以前在scala中用到过,但是单纯的SQL中还是第一次遇见,记录入册。
示例1:
-- 按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩 (case when 不影响其他聚合函数的使用)
select *
from (select SId as "学号",
sum(case CId when '01' then score end) as "课程1",
sum(case CId when '02' then score end) as "课程2",
sum(case CId when '03' then score end) as "课程3",
avg(score) avgSorce
from sc
group by SId
order by avgSorce desc )a;
示例2:
-- 统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[60-0]
select *
from(select CId,
sum(case when score >= 85 then 1 else 0 end) "100-85",
sum(case when score >= 70 and score < 85