PostgreSQL HAVING子句

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 有如下记录:

# select * from COMPANY;
 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)

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

testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) < 2;

这将产生以下结果:

  name
 -------
  Teddy
  Paul
  Mark
  David
  Allen
  Kim
  James
(7 rows)

现在,让我们来创建COMPANY 表于的三条记录使用下面的INSERT语句:

INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00);
INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00);
INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00);

现在我们的表名称重复的记录:

  id | name  | age | address      | salary
 ----+-------+-----+--------------+--------
   1 | Paul  |  32 | California   |  20000
   2 | Allen |  25 | Texas        |  15000
   3 | Teddy |  23 | Norway       |  20000
   4 | Mark  |  25 | Rich-Mond    |  65000
   5 | David |  27 | Texas        |  85000
   6 | Kim   |  22 | South-Hall   |  45000
   7 | James |  24 | Houston      |  10000
   8 | Paul  |  24 | Houston      |  20000
   9 | James |  44 | Norway       |   5000
  10 | James |  45 | Texas        |   5000
(10 rows)

下面的例子会显示名称数量大于1的记录:

testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) > 1;

这将产生以下结果:

 name
-------
 Paul
 James
(2 rows)

    点赞