1、聚合函数。
求和sum()、平均值avg()、最大值max()、最小值min()、个数统计count()。
-- 统计指定电影的上映期间的累计票房和、平均票房
select sum(leijipiaofang),avg(leijipiaofang)
from north_american_box_office
where zhongwenpianming like'%速度与激情%'
-- 统计指定电影的最长上映天数,最短上映天数
select max(shangyingtianshu),min(shangyingtianshu)
from north_american_box_office
where zhongwenpianming like '%速度与激情%'
2、字符串函数。
2.1 length(str) : 统计字节长度;char_length(str) : 统计字符长度(字符个数)。
-- 查询员工姓名的字符长度和员工身份证的字节长度。
select emp_name,
char_length(emp_name),
id_card_no,
length(id_card_no)
from employee_info
-- 举例 :查找employee_info表中身份证号码不正确的数据
select *
from employee_info
where char_length(id_card_no) not in(18 , 15)
2.2 sub_str(s,n,len):从字符串s的n位置开始截取长度为len的字符。
-- 截取手机号码的后四位
select emp_name,
phone_number,
substr(phone_number,8,4)
from employee_info
2.3 right(s,n) : 从字符串s的右端(从后往前)截取n个字符;left(s,n) : 从字符串s的左端(从前往后)截取n个字符。
-- 截取手机号码的后四位
select emp_name,
phone_number,
right(phone_number,4)
from employee_info
2.4 insert(s1,x,len,s2 )将字符串s1中x位置开始len长度的字符内容,使用s2来替换。
-- 查找所有员工的手机号码,中间四位用****代替
select emp_name,
phone_number,
insert(phone_number,4,4,'****')
from employee_info
2.5 replace(s,s1,s2)将字符串s中的s1内容替换为s2.
-- 替换敏感词
select replace('我爱北京天安门,天安门上太阳升','天安门','***') as '测试字符串'
3、日期函数。
3.1 current_date() : 当前系统日期;current_time() : 当前系统时间;now() : 当前系统日期 + 时间。
-- 获取当前系统日期,获取当前系统时间,获取当前系统时间 + 日期
select current_date(),current_time(),now()
3.2 分别获取各个部分的日期值。
- date(d) : 提取当前日期时间中的日期部分
- year(d):提取当前日期时间中的年部分
- month(d):提取当前日期时间中的月部分
- day(d) : 提取当前日期时间中的每月中的第N天
- quarter(d):提取当前日期时间中的季度部分
-- date(d) : 提取当前日期时间中的日期部分
-- year():提取当前日期时间中的年部分
-- month():提取当前日期时间中的月部分
-- day(d) : 提取当前日期时间中的每月中的第N天
-- quarter():提取当前日期时间中的季度部分
select access_datetime,
date(access_datetime),
year(access_datetime),
month(access_datetime),
day(access_datetime),
quarter(access_datetime)
from access_log
order by access_datetime desc
LIMIT 1000
-- 计算每个员工的年龄
select emp_name,
year(current_date()) - substr(id_card_no,7,4) as '年龄'
from employee_info
3.3 按照表达式,获取日期时间的各个部分值
- 表达式: extract(type from d )
- type = year 获取年份。
- type = month 获取月份。
- type = day 获取一月的第几天。
- type = quarter 获取第几季度。
- type = week 获取周。
- type = hour 获取小时。
- type = minute 获取分钟。
- type = second 获取秒。
-- 查找访问日志中所有凌晨3点的记录
select *
from access_log
where extract(hour from access_datetime) = 3
版权声明:本文为qq_43852319原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。