1、count 使用
1.1 查询employee表中记录数:
SELECT COUNT(*) FROM employee;
1.2 查询员工表中有绩效的人数:
SELECT COUNT(performance) FROM employee;
1.3 查询员工表中月薪大于2500的人数:
SELECT COUNT(*) FROM employee WHERE salary > 2500;
1.4 统计月薪与绩效之和大于5000元的人数:
SELECT COUNT(*) FROM employee WHERE IFNULL(salary,0)+IFNULL(performance,0)>5000;
1.5 查询有绩效的人数,和有管理费的人数:
SELECT COUNT(performance),COUNT(manage) FROM employee;
2、SUM 和MAX和MIN 的使用
1、查询所有雇员月薪和
SELECT SUM(salary) FROM employee;
2、查询所有雇员月薪和,以及所有雇员绩效和
SELECT SUM(salary),SUM(performance) FROM employee;
3、 查询所有雇员月薪+绩效和
SELECT SUM(salary+IFNULL(performance,0)) FROM employee;
4、统计所有员工平均工资
SELECT AVG(salary) FROM employee;
5、 查询最高工资和最低工资
SELECT MAX(salary),MIN(salary) FROM employee;
3、分组查询
1、 将查询结果按照1个或者多个字段进行分组,字段值相同的为1组
SELECT gender FROM employee GROUP BY gender;
2、把相同的数据去掉
SELECT gender,GROUP_CONCAT(name) FROM employee GROUP BY gender;
4、分组查询-使用
1、在一组里面所有男性名字和女性名字
SELECT gender,GROUP_CONCAT('name') FROM employee GROUP BY gender;
2、 所有男性工资和女性工资
SELECT gender,GROUP_CONCAT(salary) FROM employee GROUP BY gender;
3、对某一个部门进行分组,查看每个部门薪资信息都罗列出来
SELECT department,GROUP_CONCAT(salary) FROM employee GROUP BY department;
5、GROUP BY + 聚合函数
1、查看部门平均薪资
SELECT department,GROUP_CONCAT(salary),SUM(salary) FROM employee GROUP BY department;
2、查看每个部门的最高薪资
SELECT department,GROUP_CONCAT(salary),MAX(salary) FROM employee GROUP BY department;
3、查看每个部门的最低薪资
SELECT department,GROUP_CONCAT(salary),MIN(salary) FROM employee GROUP BY department;
4、查询每个部门的部门名称和每个部门的工资和
SELECT department,GROUP_CONCAT(salary),SUM(salary) FROM employee GROUP BY department;
5、查询每个部门的部门名称和每个部门的人数
SELECT department,GROUP_CONCAT(name),COUNT(*) FROM employee GROUP BY department;
6、查询每个部门的部门名称以及每个部门工资大于1500的人数
SELECT name,salary FROM employee WHERE salary>1500;
SELECT department,GROUP_CONCAT(salary),COUNT(*) FROM employee WHERE salary>1500 GROUP BY department;
6、GROUP BY + having
1、把所有部门进行分组
SELECT department FROM employee GROUP BY department;
2、每一组有哪些薪资,以及薪资总和
SELECT department,GROUP_CONCAT(salary),SUM(salary) FROM employee GROUP BY department;
3、完成
SELECT department,GROUP_CONCAT(salary),SUM(salary) FROM employee GROUP BY department HAVING SUM(salary)>9000;
7、HAVING和WHERE的区别
HAVING是在分组后对数据进行过滤;
WHERE是在分组前对数据进行过滤;
HAVING后面可以使用分组函数(统计函数);
WHERE后面不可以使用分组函数;
WHERE是对分组前记录的条件,如果某行记录没有满足where子语句的条件,那么这行记录不参与分组;而HAVING是对分组后的数据约束;
1、查询工资大于2000的,工资总和大于6000的部门名称以及工资和;
各部门工资
各部门工资总和
各部门工资总和大于6000
各部门工资总和大于6000降序排序
2.、查询工资大于2000
SELECT salary FROM employee WHERE salary>2000;
3、工资总和
SELECT department,GROUP_CONCAT(salary),SUM(salary) FROM employee WHERE salary > 2000 GROUP BY department HAVING SUM(salary)>9000;
ORDER BY SUM(salary) DESC;
8、书写顺序,执行顺序
书写顺序SELECT --> FROM --> WHERE --> GROUP BY --> HAVING --> ORDER BY --> LIMIT
执行顺序FROM => WHERE => GROUP BY => HAVING => SELECT => ORDER BY => LIMIT