09 MySQL_SQL日期函数和聚合函数
日期相关的函数
- seclect 'helloworld';
1. 获取当前时间 now();
select now();
2.获取当前的日期 curdate();
select curdate();
3 获取当前的时间 curtime();
select curtime();
4. 从年月日时分秒中 提前年月日 和 提前年月日
select date();//提取年月日
select date(now());
select date(created_time) from t_item;
select time();//提取年月日
select time(now());
select date(created_time) from t_item;
5.从年月日中提取时间分量 extract(year from now())
select extract(year from now());
select extract(month from now());
select extract(day from now());
select extract(hour from now());
select extract(minute from now());
select extract(second from now());
//查询每个员工的入职年份
select extract(year from hiredate) from t_item;
6.日期格式化
- 格式:
%Y 四位年 %y 两位年
%m 两位月 %c 一位月
%d 日
%H 24小时 %h12小时
%i 分
%s 秒
- delete_format(时间,格式)
- 举例: 把时间默认格式转成年月日时分秒
select date_format(now(),'%Y年%m月%d日 %H时%i分%s秒');
- 把非标准格式时间转回默认格式 :
- str_to_date('非标准格式的时间',格式)
- 举例:把14.08.2018 08:00:00 转成标准格式
select str_to_data('14.08.2018 08:00:00','%d.%m.%Y %H:%i:%s')
if null(x,y)函数
-
age = ifnull(x,y)
-
如果x的值为null则age=y 如果x的值不为null,则age=x
1.把员工表中奖金为null的改为0 其他的不变; update emp set sal=ifnull(sal,0);
聚合函数
-
聚合函数用于对多行数据进行统计(平均值,最大值,最小值,求和,统计数量)
-
包括统计方式有:
- 平均值 avg(字段名)
- 最大值 max(字段名)
- 最小值 min(字段名)
- 求和 sum(字段名)
- 计数 count(字段名或*)
--1.平均值 //查询所有员工的平均工资 select avg(sal) from emp; //查询10号部门的平均工资; select avg(sal) from emp where deptid=10; //查询戴尔商品的平均单价 select avg(price) from emp where title like '%戴尔%'; --2.最大值max(字段名) //查询程序员的最高工资 select max(sal) from emp where job='程序员'; --3.最小值min(字段名) //查询2号部门的最低工资 select min(sal) from emp where deptId=2; --4.求和sum(字段名) //查询3号部门的工资总和 select sum(sal) from emp where deptId=3; --5.计数count(字段名或*) //查询1号部门的人数 select count(*) from emp where deptId=1;
浙公网安备 33010602011771号