zoukankan      html  css  js  c++  java
  • SqlServer 多表连接、聚合函数、模糊查询、分组查询应用总结(回归基础)

    --exists 结合 if else 以及 where 条件来使用判断是否有数据满足条件
    select * from Class where Name like '%[1-3]班'
    if (not exists(select * from Class where len(Name)>=5))
        select '满足条件'
    else
        select '不满足条件'
    --in not in 用来做范围判断
    select * from Student where ClassId  in(select Id from Class) and ClassId%2=0
    --表连接 使用场景:当你要查询的数据发布在多张表中,且这几张表存在关联关系
    --2种表连接 
    --1.内连接:会去掉用不到的数据
    select * from Class
    select * from Student
    --制作表连接的步骤 1.确定起始表 2.把所有表连接起来,并用on关键字设置引用关系 3.选择需要的列
    select * from Class 
    inner join Student on 
    Class.Id=Student.ClassId
    --2.外连接
    --2.1左外连接 2.2右外连接 2.3全连接
    --会显示两张表公有的数据,确定会显示左边表的数据,右边表没有的则显示为null
    select * from Class left join Student on Class.Id=Student.ClassId
    --与左连接相反,确定会显示右边表的数据,左边表没有的则显示为null
    select * from Class right join Student on Class.Id=Student.ClassId
    --全连接:左外连接+右外连接,除了显示公有的数据,还会把多余的数据显示
    select * from Class full join Student on Class.Id=Student.ClassId
    --聚合函数:多用于统计数据和分析数据上
    --count()条数:通常情况下不要和*搭配使用,要和一个常量数字使用,因为常量的性能较快
    --max,min也可以对字符串、时间类型进行操作
    select count(*) from Class
    select count(Id) from Class
    select count(0) from Class    --推荐写法
    --max()最大值
    select max(Id) from Class
    --min()最小值
    select min(Id) from Class
    --sum()求和
    select sum(Id)from Class
    --avg()平均数
    select avg(Id) from Class
    --分组查询:结合聚合函数一起使用关键字后面可以使用
    --分组查询中 select 关键字可以使用聚合函数或出现在group by字句中的列
    --注意:如果你还想要在select 后面显示其他列的值,你可以在group by字句后继续写与分组字段同表的其他查询的字段,记住是同表!!!
    select count(0) 数量,Class.Name,Class.Id from Class inner join Student on Class.Id=Student.ClassId
    group by Class.Name,Class.Id
    having count(0) >=2
    --where和having区别:where是对表中所有的数据的筛选,having是对分组统计后的数据进行筛选
  • 相关阅读:
    docker学习数据卷挂载方式
    接口自动化CIJenkins
    linux安装docker
    docker学习容器备份
    Python实现简易的ORM模型
    Python队列
    selenium实现绕过登录
    docker学习镜像常用操作命令
    docker学习容器常用命令
    把握趋势,成为赢家
  • 原文地址:https://www.cnblogs.com/hcyesdo/p/13434500.html
Copyright © 2011-2022 走看看