SqlServer 多表连接、聚合函数、模糊查询、分组查询应用总结(回归基础)
2024-10-19 15:24:19
--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是对分组统计后的数据进行筛选
最新文章
- 【Java】JavaWeb权限管理
- netcore web.config ConnectionStrings AppSettings
- 利用javascript、php和ajax实现计算器
- mongoDB数据库备份
- github 学习笔记【一】
- web应用中webapp. root重用问题解决方案
- linux服务器修改ftp默认21端口方法
- ResourceDictionary 和 XAML 资源引用
- swift2.0 UIImagePickerController 拍照 相册 录像
- FFMPEG H264/H265 编码延迟问题
- hadoop-2.6.0源码编译问题汇总
- FusionCharts MSBar2D图
- 吴恩达机器学习笔记59-向量化:低秩矩阵分解与均值归一化(Vectorization: Low Rank Matrix Factorization &; Mean Normalization)
- RabbitMQ详解(二)------消息通信的概念
- 使用systemtap调试工具分析MySQL的性能
- ransom-note
- 在Foreda8上试安装Apchehttpd-2.4.6.tar.gz
- HTTP 499 状态码 nginx下 499错误
- 安装 Zsh 及 Oh-my-zsh
- 001-window下运行linux