模糊查询
like关键字和通配符
%:代表匹配0个字符,1个字符或多个字符
_:代表匹配有且只有一个字符
[ ]:代表匹配范围内
[ ^ ]:代表匹配不在范围内
举例:
1.查询姓刘的员工信息
% 刘字后面匹配的字符数
select * from People where Name like '刘%'
2.查询名字中含有"尚"的员工信息
select * from people where Name like '%尚%'
3.查询名字中含有"尚"或者’史’的员工信息
select * from people where Name like '%尚%' or Name like '%史%'
4.查询姓刘的员工信息,名字是两个字(刘字后面仅匹配一个字符)
select * from People where Name like '刘_'
---SUBSTRING 起始字符从1开始
select * from People SUBSTRING(Name,1,1) = '刘' and LEN(Name) = 2
5.查询出电话号码开始为138,第四位好像是7或者8 最后一位是5的
select * fromf People where Phone like '138[7,8]%5'
6.查询出电话号码开始为138,第四位好像是2-5 最后一位不是2和3
select * from People where Phone like '138[2-5]%[^2,3]'
聚合函数
count:求数量
max:求最大值
min:求最小值
sum:求和
avg:求平均值
举例
1.求员工总人数
select count(*) 数量 from People
2.查询工资最高的,工资总和,工资平均值
ROUND(值,小数位数):保留几位小数
select MAX(Salary) 工资最高 from People
select SUM(Salary) 工资总和 from People
select ROUND(AVG(Salary),2) 工资平均值 from People
3.查询出工资比平均工资高的人员信息
select * from People where Salary > (select AVG(Salary) from People)
4.求年龄
select *,year(getdate()) - year(Birth) from People
5.求差值
DATEDIFF(a,b,c)
a:单位
运算表达式:c-b
DATADIFF(year,‘1991-1-1’,‘1995-5-5’) 结果 = 4
分组查询
group by 字段名
举例:
1.根据员工所在地区分组统计员工人数,员工工资总和,平均工资,最高工资和最低工资
select Address 地区, count(*) 数量,sum(Salary) 工资总和, avg(Salary) 平均工资, max(Salary)最高工资, min(Salary) 最低工资 from People group by Address
1.根据员工所在地区分组统计员工人数,员工工资总和,平均工资,最高工资和最低工资,要求晒宣传员工人数至少在2人及以上的记录,并且1985年及以后出生的员工不参与统计
NOTE:一般的条件直接写在group by前面 使用where关键字
包含聚合函数的条件需写在group by后面,用HAVING关键字修饰
select Address 地区,count(*) 员工人数,sum(Salary) 工资总和,
avg(Salary) 平均工资,max(Salary) 最高工资,min(Salary) 最低工资 from People
where Birth > '1985-1-1'
group by Address
HAVING count(*) >= 2