流程控制函数
SELECT IF(commission_pct IS NULL, '没奖金 呵呵', '有奖金 嘻嘻') AS 备注
FROM employees;
SELECT salary, department_id,
CASE department_id
WHEN 30 THEN salary*1.1
WHEN 40 THEN salary*1.2
WHEN 50 THEN salary*1.5
ELSE salary
END AS 新工资
FROM employees;
SELECT salary,
CASE
WHEN salary>20000 THEN 'A'
WHEN salary>15000 THEN 'B'
WHEN salary>10000 THEN 'C'
ELSE 'D'
END AS 工资级别
FROM employees;
分组函数
功能:用作统计使用,又称为聚合函数或统计函数或组函数 分类:sum 求和、avg 平均值、max 最大值、min 最小值、count 计算个数
参数支持哪些类型:
- sum, avg一般用于处理数值型;max, min, count可以处理任何类型;
- 以上分组函数都忽略null值:
- 可以和distinct搭配使用,实现去重;
- 和分组函数一同查询的字段有限制,一般要求是group by后的字段;
count函数的详细介绍
- count(字段)
- count(*):只要有一行不为null就加1
- count(1):统计函数
效率: MYISAM存储引擎下,count()的效率最高 INNODB存储引擎下,count()和count(1)效率差不多
案例:查询员工表中最大入职时间和最小入职时间的相差天数(diffrence)
SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) DIFFRENCE
FROM employees;
分组查询
Group By基本语法
SELECT column,group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column]
注意:
查询列表比较特殊,要求是分组函数或者group by后出现的字段
特点:
1、分组查询中的筛选条件分为两类
数据源 位置 关键字
分组前筛选 原始表 group by子句前 where
分组后筛选 分组后的结果集 group by子句后 having
(1)分组函数做条件肯定放在having子句中;
(2)能用分组前筛选的优先使用分组前筛选
案例
SELECT AVG(salary)
FROM employees
GROUP BY department_id;
SELECT AVG(salary),department_id
FROM employees
WHERE email LIKE '%a%'
GROUP BY department_id;
SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id
HAVING COUNT(*)>2;
SELECT manager_id,MIN(salary)
FROM employees
WHERE manager_id>102
GROUP BY manager_id
HAVING MIN(salary)>5000;
SELECT COUNT(*),LENGTH(last_name) len_name
FROM employees
GROUP BY LENGTH(last_name)
HAVING COUNT(*)>5;
|