准备工作:
为T_Employee表增加两列,分别为表示其所属分公司的FSubCompany字段和表示其所属部门的FDepartment。
ALTER TABLE T_Employee ADD FSubCompany VARCHAR(20);
ALTER TABLE T_Employee ADD FDepartment VARCHAR(20);
两个字段添加完毕后,将表中原有数据行的这两个字段值更新,执行下面的SQL语句:
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="Development" WHERE FNumber="DEV001";
UPDATE T_Employee SET FSubCompany="ShenZhen",FDepartment="Development" WHERE FNumber="DEV002";
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="HumanResource" WHERE FNumber="HR001";
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="HumanResource" WHERE FNumber="HR002";
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="InfoTech" WHERE FNumber="IT001";
UPDATE T_Employee SET FSubCompany="ShenZhen",FDepartment="InfoTech" WHERE FNumber="IT002";
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="Sales" WHERE FNumber="SALES001";
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="Sales" WHERE FNumber="SALES002";
UPDATE T_Employee SET FSubCompany="ShenZhen",FDepartment="Sales" WHERE FNumber="SALES003";
数据分组:group by,常和聚合函数一起使用
查看公司员工有哪些年龄段的:
SELECT FAge FROM T_Employee GROUP BY FAge
运行结果:
FAge
22
23
25
27
28
实际上:把年龄相同的放到一组了,如图必须放在select语句之后,若存在where,也要放在where之后
SELECT FAge FROM T_Employee WHERE FSubCompany = "Beijing" GROUP BY FAge
需要分组的所有列都必须位于GROUP BY子句的列名列表中,也就是没有出现在GROUP BY子句中的列(聚合函数除外)是不能放到SELECT语句后的列名列表中的。
比如下面的SQL语句是错误的:
SELECT FAge,FSalary FROM T_Employee GROUP BY FAge
salary
这个字段没有在分组的子句中,且每人工资不同 则不存在可以代表本组工资水平的salary字段。
每组中员工的平均工资却是能够代表本组统一工资水平的,所以可以对FSalary使用聚合函数,下面的SQL语句是正确的:
SELECT FAge,AVG(FSalary) FROM T_Employee GROUP BY FAge
GROUP BY子句中可以指定多个列,只需要将多个列的列名用逗号隔开即可。
指定多个分组规则以后,数据库系统将按照定义的分组顺序来对数据进行逐层分组,首先按照第一个分组列进行分组,然后在每个小组内按照第二个分组列进行再次分组……逐层分组,从而实现“组中组”的效果,而查询的结果集是以最末一级分组来进行输出的。
如下面的SQL语句将会列出所有分公司的所有部门情况:
SELECT FSubCompany,FDepartment FROM T_Employee GROUP BY FSubCompany,FDepartment
执行结果:group by 与聚合函数一起使用
查看每个年龄段的员工的人数
SELECT FAge,COUNT(*) AS CountOfThisAge FROM T_Employee GROUP BY FAge
将上表指定按照FSubCompany字段进行排序(默认是用年龄进行排序)
SELECT FSubCompany,FAge,COUNT(*) AS CountOfThisSubCompAge FROM T_Employee GROUP BY FSubCompany,FAge ORDER BY FSubCompany
其他聚合函数可以在分组中使用:
统计每个公司中的工资的总值
SELECT FSubCompany,SUM(FSalary) AS FSalarySUM FROM T_Employee GROUP BY FSubCompany
统计每个垂直部门中员工年龄的最大值和最小值:
SELECT FDepartment,MIN(FAge) AS FAgeMIN,MAX(FAge) AS FAgeMAX FROM T_Employee GROUP BY FDepartment