SQL_5_子句
接下来讲到的子句有:
WHERE
STARTING WITH
ORDER BY
GROUP BY
HAVING
WHERE: 使用频率仅次于SELECT和FROM
STARTING WITH: 附加于WHERE子句上,作用于LIKE(exp%)相似
SELECT PAYEE,AMOUNT,REMARKS FROM CHECKS WHERE PAYEE LIKE('Ca%');
SELECT PAYEE,AMOUNT,REMARKS FROM CHECKS WHERE PAYEE STARTING WITH('Ca%');
ORDER BY: 提供了对输出的结果进行排序的方法。ORDER BY DESC表示降序排列来代替默认的升序排列,ASC按升序排列
按CHECK#列排序:SELECT * FROM CHECKS ORDER BY CHECK#;
等价于:SELECT * FROM CHECKS ORDER BY 1; 用第一列进行排序
按PAYEE降序排列:SELECT * FROM CHECKS ORDER BY PAYEE DESC;
ORDER BY可以使用多个字段,按PAYEE和REMARKS进行排序:
SELECT * FROM CHECKS ORDER BY PAYEE,REMARKS;
第一列按字母的正顺排列,第二列按字母的逆序排列:
SELECT * FROM CHECKS ORDER BY PAYEE ASC,REMARKS DESC;
GROUP BY: 分组,当要求分组结果返回多个数值时不能再在SELECT子句中使用除分组列以外的列,否则会导致错误的返回值。
每一个PAYEE的总花费:SELECT PAYEE,SUM(AMOUNT) FROM CHECKS GROUP BY PAYEE;对SELECT结果进行分组后再应用汇总函数
SELECT PAYEE,SUM(AMOUNT),COUNT(PAYEE) FROM CHECKS GROUP BY PAYEE;
HAVING: 允许将汇总条件作为结果,也可以使用多个汇总条件。
对输出的结果进行分组,并显示每一组的平均工资:SELECT TEAM,AVG(SALARY) FROM ORGCHART BROUP BY TEAM;
返回分组后平均工资少于38000的组:
SELECT TEAM,AVG(SALARY) FROM ORGCHART WHERE AVG(SALARY) < 38000 BROUP BY TEAM;
上边的写法是错的,由于汇总函数不能工作在WHERE子句中,所以只能使用
SELECT TEAM,AVG(SALARY) FROM ORGCHART GROUP BY TEAM HAVING AVG(SALARY)<380000;
可以使用多个汇总条件,按TEAM进行分组并符合平均病假大于25天和平均年假少于20天的组:
SELECT TEAM,AVG(SICKLEAVE),AVG(ANNUALLEAVE) FROM ORGCHART GROUP BY TEAM HAVING AVG(SICKLEAVE)>25 AND AVG(ANNUALLEAVE)<20;
可以在HAVING中使用在SELECT中没有指出的字段进行汇总,返回组中成员大于1的组:
SELECT TEAM,AVG(SICKLEAVE),AVG(ANNUALLEAVE) FROM ORGCHART GROUP BY TEAM HAVING COUNT(TEAM) >1;
在HAVING中可以使用其他的逻辑操作符:
SELECT TEAM,MIN(SALARY),MAX(SALARY) FROM ORGCHART GROUP BY TEAM HAVING AVG(SALARY)>37000 AND MIN(SALARY)>32000;
子句的综合应用