您的位置:首页 > 数据库

Microsoft SQL Server学习(五)--操作符聚合函数

2017-10-08 16:49 316 查看
算术运算符

逻辑运算符

比较运算符

聚合函数

算术运算符(+ - * / )
select score*2 as 成绩翻倍 from class_A

update  class_A
set score=score+20
where score<70

update  class_A
set score=score-20
where score>70

update  class_A
set score=score/2
where score>70

逻辑运算符(and/or/between A and B )

select * from class_A
select * from class_A where score >=80 and sex = 'male'
select * from class_A where score >=80 or sex = 'male'
select * from class_A where score between 60 and 80

比较运算符(< > <= >= <> != = )

介词查询 in(a,b…):在a、b中查询

Select * from class_A
Where score in(60,80)

去除重复值 distinct
Select distinct 列名 from 表名

查询前N条数据 top

Select top 2 * from class_A

查询前百分比条数据 top percent
Select top 20 percent * from class_A

查询后N条数据
Select top 4 * from class_A
Where score not in
(select top 3 score from class_A)

模糊查询like
Select * from class_A where name like '%娜%'
Select * from class_A where name like '文_'
Select * from class_A where name like '[文][章]'
Select * from class_A where name like '[李%]'
Select * from class_A where name like '%娜%'

%  表示任意通配
_  表示一个字符通配
[] 表示集合([a-z]、[123]、[中山]、[中][山])
[中山]等价于[中][山]
[]中文要使用%或_

排序order by(默认为升序)
升序
Select * from class_A
Order by score
降序
Select * from class_A
Order by score desc

分组group by
在分组时,查询字段必须与分组的字段一致或者查询条件使用的是聚合函数

聚合函数
(1)统计函数
1)Count():统计总数
2)Max():最大值
3)Min():最小值
4)Avg():平均值
5)Sum():总和
6)Var():方差

使用having进行分组筛选
Select 列名1,聚合函数 from 表名
Group by 列名1
Having 聚合函数条件

select sum(score) as 总分 from class_A
select count(name) as 总人数 from class_A
select max(score) as 最高分 from class_A
select min(score) as 最低分 from class_A
select avg(score) as 平均分 from class_A

select name,AVG(score)  from class_A group by name,score
having  score > 60

select name,avg(score)  from class_A group by sex,name
having avg(score) <68 and sex='male'

select avg(score) as 平均分 from class_A where sex='male'
select avg(score) as 平均分 from class_A where sex='female'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql server