SQL基础知识点总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/youngmiffy/article/details/84482177

SQL基础知识点总结

常用语句的执行顺序:
from–on–join–where–group by–cube/rollup–having–select–distinct–order by–limit

一、基础查询

select distinct product,number*2 as "数据",*,'商品' as "类型"
from table 1
where dt='2018-11-09'
and  not number>10
or product is not null
--AND 的运算优先级高于OR
/*注释语法的表示之二*/

二、聚合

  • 聚合函数:count sum avg max min
    需要注意的是null在参与计算的时候,计算合计值时null处理为0,计算平均值时null处理为0,但是数量上增加了一个;max min 处理的时候不参与计算;
  • group by (聚合键/分组列)
    需要注意的是:group by自居中不能使用select中列的别名;
    where 子句中不能使用聚合函数;
  • 常见错误
    select子句中有多余的列
    group by子句中使用了列的别名
    group by结果能排序吗–不是,结果顺序随机
    where 子句中使用聚合函数
  • 聚合键所对应的条件赢还是书写在where子句中(两个原因:理解和执行速度)
    where子句=指定行所对应的条件
    having子句=指定组所对应的条件

三、排序

  • order by (排序键)
    排序键中包含null时会在开头和结尾进行汇总
    order by中可以使用列的别名
    可以使用select 子句中未出现的列和聚合函数
    不能使用列的编号(语法无误,但阅读困难,未来可能删除)

四、复杂查询

  • 视图
create view 视图名称(视图列名1,视图列名2)
AS
<select 语句>

定义视图时不能使用order by子句
对视图进行更新时需要满足一些条件

  • 标量子查询
    必须且只能返回1行1列的结果
  • 关联子查询(和标量子查询的关系感觉有点儿矛盾?)
    举例:选出各分类中价格超过均值以上的分类
select 商品种类,商品名称,价格
from table1 as P1
where C>(select avg(价格)
		   from table2 as P2
		   where P1.商品种类=P2.商品种类
		   group by 商品种类)

五、函数、谓词、CASE表达式

  • 函数
    算术函数:abs/mod/round
    字符串函数:concat/length/lower/replace/substring/upper
    日期函数:current_date/current_time/current_timestamp/extract
    转换函数:cast/coalesce
    聚合函数:max/min/avg/count/sum
  • 谓词
    like/between/is null/in/exists
  • case when then else end

六、集合运算(union/join)

  • union
    作为运算对象的记录的列数必须相同
    作为运算对象的记录中列的类型必须一致
    可以使用select,但order by 只能在最后使用一次
    包含:
    union all:并集,包含所有重复行
    intersect:交集
    except:差集
  • join
    inner join:内连接 两个表都存在的信息选出来
    outer join:外链接,任何一个表中存在的所有数据都选出来
    cross join:笛卡尔积,是所有其它join查询的基础

七、SQL高级处理

  • 窗口函数语法 <窗口函数> over (partition by <列清单> order by <列清单>),partition by 在横向上进行了分组,order by 在纵向上进行了排序
  • 必须用在select子句,但是不能用在where/group by子句中
    种类:rank(相同位次跳过,1/1/3)/dense_rank(相同位次不跳过1/1/2)/row_number(唯一位次1/2/3)
    补充说明:row number 可以解决取最大值然后再inner join去重的方法,特别简单;
  • 计算移动平均
avg() over(order by 字段 rows 2 preceding) as name
avg() over(order by 字段 rows 2 following) as name
avg() over(order by 字段 rows between 1 preceding and 1 following) as name
  • rollup 同时得出合计和小计 语法:group by rollup (字段1 字段2),但是如果字段有空的情况就会出现两个有歧义的行,需要注意,为了避免这种情况,请使用grouping
    补充说明:roll up 可以解决group by只有小组合计,没有总合计的问题,省去了union的麻烦。
  • grouping
select 
      case when grouping(字段1)=1 then '字段1合计' else 字段1 end as name1
      case when grouping(字段2)=1 then '字段2合计' else 字段2 end as name2
      sum(字段3) as 字段3合计
from table1
group by rollup(字段1,字段2)
--相当于group by() 和 group by (字段1)
  • cube
select 
      case when grouping(字段1)=1 then '字段1合计' else 字段1 end as name1
      case when grouping(字段2)=1 then '字段2合计' else 字段2 end as name2
      sum(字段3) as 字段3合计
from table1
group by cube(字段1,字段2)
--相当于group by() 和 group by (字段1)和group by(字段2)

猜你喜欢

转载自blog.csdn.net/youngmiffy/article/details/84482177