标签:排序 font order 邮件 表达 min iss 字段 desc
1 #分组查询 2 /* 3 语法: 4 select 分组函数,列 (要求出现在group by 的后面) 5 from 表 6 【where 筛选条件】 7 group by 分组的列表 8 【order by 字句】 9 10 特点: 11 1.分组查询中的筛选分为两类 12 数据源 位置 关键字 13 分组前筛选 原始表 group by字句前面 where 14 分组后筛选 分组后的结果集 group by字句后面 having 15 2.分组函数做条件肯定放在having字句中 16 3.能用分组前筛选优先选用分组前筛选 17 4.group by支持单个字段分组,也支持多个字段分组(多个字段用逗号隔开没有顺序要求) 18 5.也可以增加排序(拍寻放在整个分组查询的最后) 19 */ 20 21 #案例1:查询每个工种的平均工资 22 SELECT MAX(salary),job_id 23 FROM employees 24 GROUP BY job_id; 25 26 #案例2:查询每个位置上的部门个数 27 SELECT COUNT(*),location_id 28 FROM departments 29 GROUP BY location_id; 30 31 #一.添加筛选条件 32 #案例1:查询邮件中包含a字符,每个部门的平均工资 33 34 SELECT AVG(salary),department_id 35 FROM employees 36 WHERE email LIKE ‘%a%‘ 37 GROUP BY department_id; 38 39 #案例2:查询有奖金的每个领导手下员工最高工资 40 41 SELECT MAX(salary),manager_id 42 FROM employees 43 WHERE commisson_pct IS NOT NULL 44 GROUP BY manager_id; 45 46 #案例3:那个部门的员工个数大于2 47 #1)查询每个部门的员工个数 48 SELECT COUNT(*),department_id 49 FROM employees 50 GROUP BY department_id; 51 #2)根据1的结果进行筛选,查询哪个部门的员工个数>2 52 SELECT COUNT(*),department_id 53 FROM employees 54 GROUP BY department_id 55 HAVING COUNT(*)>2; 56 57 #案例4:查询每个工种有奖金的员工的最高工资>12000的公众编号和最高工资 58 59 #1).查询每个工种有奖金的员工的最高工资 60 SELECT MAX(salary),jobs_id 61 FROM employees 62 WHERE commisson_pct IS NOT NULL 63 GROUP BY job_id; 64 65 #2).根据1)的结果继续筛选,最高工资>12000 66 SELECT MAX(salary),jobs_id 67 FROM employees 68 WHERE commisson_pct IS NOT NULL 69 GROUP BY job_id 70 HAVING MAX(salary)>12000; 71 72 #案例4:查询领导编号>102的每个领导手下的最低工资>5000的领导编号是哪个,以及其最低工资 73 74 #1)查询每位领导手下员工固定最低工资 75 SELECT MIN(salary),manager_id 76 FROM employees 77 GROUP BY manager_id; 78 #2).添加筛选条件 编号大于102 79 SELECT MIN(salary),manager_id 80 FROM employees 81 WHERE manager_id > 102 82 GROUP BY manager_id; 83 #3).最低工资大于5000 84 SELECT MIN(salary),manager_id 85 FROM employees 86 WHERE manager_id > 102 87 GROUP BY manager_id; 88 HAVING MIN(salary)>5000; 89 90 #二.按表达式或函数分组 91 92 #案例:按员工姓名长度分组,查询每一组员工个数,筛选员工个数大于5的有哪些 93 94 #1).每个长度的员工个数 95 96 SELECT COUNT(*),LENGTH(last_name) len_name 97 FROM employees 98 GROUP BY LENGTH(last_name); 99 100 #2).添加筛选条件 101 #注意group by having 都支持别名 102 SELECT COUNT(*) c ,LENGTH(last_name) len_name 103 FROM employees 104 GROUP BY len_name 105 HAVING c>5; 106 107 #三.按多个字段进行分组 108 109 #案例:查询每个部门每个工种的员工平均工资 110 111 SELECT AVG(salary),department_id,job_id 112 FROM employees 113 GROUP BY job_id,department_id; 114 115 116 #四.添加排序 117 #案例:查询每个部门每个工种的员工的平均工资,并且按平均工资的高低显示 118 SELECT AVG(salary),department_id,job_id 119 FROM employees 120 WHERE department_id IS NOT NULL 121 GROUP BY job_id,department_id 122 HAVING AVG(salary)>10000 123 ORDER BY AVG(salary) DESC;
DQL
标签:排序 font order 邮件 表达 min iss 字段 desc
原文地址:https://www.cnblogs.com/zhengyinboke/p/11865858.html