PostgreSQL HAVING子句

PostgreSQL HAVING子句

HAVING子句允许我们选择出函数结果满足某些条件的特定行。

WHERE子句对所选列进行条件限制,而HAVING子句对GROUP BY子句创建的分组进行条件限制。

语法

在SELECT查询中,HAVING子句的位置如下所示:

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

HAVING子句必须在查询中紧跟GROUP BY子句,并且如果使用的话,必须在ORDER BY子句之前。下面是包括HAVING子句在内的SELECT语句的语法:

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)

现在,让我们使用以下INSERT语句在COMPANY表中创建三个额外的记录。

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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程