发布于 2015-07-25 11:52:54 | 239 次阅读 | 评论: 0 | 来源: 网络整理

HAVING子句允许指定条件,过滤分组结果将出现在最终结果。

WHERE子句所选列的条件,而HAVING子句条件由GROUP BY子句创建分组。

语法

以下是HAVING子句的SELECT查询中的位置:


SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

HAVING子句必须遵循在GROUP BY子句中的查询,也必须先如果使用ORDER BY子句。以下是SELECT语句的语法,包括HAVING子句:


SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

例子:

考虑COMPANY表有以下记录:


ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
8           Paul        24          Houston     20000.0
9           James       44          Norway      5000.0
10          James       45          Texas       5000.0

下面的例子,这将显示记录名称计数小于2:


sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;

这将产生以下结果:


ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
2           Allen       25          Texas       15000
5           David       27          Texas       85000
6           Kim         22          South-Hall  45000
4           Mark        25          Rich-Mond   65000
3           Teddy       23          Norway      20000

以下的例子,它会显示名称数量大于2的记录:


sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2;

这将产生以下结果:


ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
10          James       45          Texas       5000
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务