当前位置:Gxlcms > 数据库问题 > 【2017-03-12】SQL Sever 子查询、聚合函数

【2017-03-12】SQL Sever 子查询、聚合函数

时间:2021-07-01 10:21:17 帮助过:11人阅读


子句的查询结果必须是一列
子句可以返回多行数据,但必须是一列

select * from 表名 where 列名 =,>,<(select * from 表名 where 列名...)

 

in/not in

列名 in(值,值,值)表示取值在后面提供的值以内,相当于 列名=值 or 列名=值 or 列名=值

例:select * from car where oil=7.4 or oil=8 or oil=8.3 与 select *from car where oil in (7.4,8,8.3) 执行结果一模一样

列名 not in(值,值,值)表示取值都不在后面提供的值以内,相当于 列名!=值 and 列名!=值 and 列名!=值

例: select * from car where oil not in (7.4,8,8.3)    与 select *from cat where oil !=7.4 and oil !=8 and oil !=8.3

 

between and     

值 between a and b 相当于 值>=a and 值<=b,表示介于a,b两者之间并且包括两者的值

 

any

值>any (a,b,c)   即取值大于a,b,c3个数之的最小值

值<any (a,b,c)   即取值小于a,b,c3个数之的最大值

all

值>all (a,b,c)     即取值大于a,b,c3个数中的最大值

值<all (a,b,c)     即取值小于a,b,c3个数中的最小值

 

*查询两个不同表中的两列数据

通过子查询和两个表中相同的一列建立联系

例:查询所有学生的Sname、Cno和Degree列。

select (select Sname from Student where Student.Sno=Score.Sno),Cno,Degree from Score

--其中Sname在Student表中,Cno和Degree在Score表中,其中两个表有Student.Sno=Score.Sno的连接

--用数据多的表做为主表来查询,其中Score为主表

 

二、聚合函数

1.max(最大值),min(最小值)

技术分享

2.avg 平均值

技术分享

3.count 计行数

 技术分享

4.sum 求和

技术分享

*使用聚合函数查询出来的数据没有列名,可以通过在聚合函数后加 as 名称  添加列名

技术分享

 

分组查询并计数升降序排列

select 列名,count(*) from 表名 group by 列名 order by count(*) asc/desc

技术分享

分组查询并计数筛选    分组之后再筛选需用having替换where

select 列名,count(*) from 表名 group by 列名 having count(*) >,<,= 值

技术分享

 

【2017-03-12】SQL Sever 子查询、聚合函数

标签:取值   行数据   数据   blog   不同   log   tween   筛选   eve   

人气教程排行