PostgreSQL GROUP BY 語句

在 PostgreSQL 中,GROUP BY 語句和 SELECT 語句一起使用,用來對相同的數據進行分組。

GROUP BY 在一個 SELECT 語句中,放在 WHRER 子句的后面,ORDER BY 子句的前面。

語法

下面給出了 GROUP BY 子句的基本語法:
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2....columnN
ORDER BY column1, column2....columnN

GROUP BY 子句必須放在 WHERE 子句中的條件之后,必須放在 ORDER BY 子句之前。

在 GROUP BY 子句中,你可以對一列或者多列進行分組,但是被分組的列必須存在于列清單中。

實例

創建 COMPANY 表(下載 COMPANY SQL 文件 ),數據內容如下:

runoobdb# 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)

下面實例將根據 NAME 字段值進行分組,找出每個人的工資總額:

runoobdb=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;

得到以下結果:

  name  |  sum
 -------+-------
  Teddy | 20000
  Paul  | 20000
  Mark  | 65000
  David | 85000
  Allen | 15000
  Kim   | 45000
  James | 10000
(7 rows)

現在我們添加使用下面語句在 CAMPANY 表中添加三條記錄:

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);

現在 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
   8 | Paul  |  24 | Houston      |  20000
   9 | James |  44 | Norway       |   5000
  10 | James |  45 | Texas        |   5000
(10 rows)

現在再根據 NAME 字段值進行分組,找出每個客戶的工資總額:

runoobdb=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;

這時的得到的結果如下:

name  |  sum
-------+-------
 Allen | 15000
 David | 85000
 James | 20000
 Kim   | 45000
 Mark  | 65000
 Paul  | 40000
 Teddy | 20000
(7 rows)

下面實例將 ORDER BY 子句與 GROUP BY 子句一起使用:

runoobdb=#  SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;

得到以下結果:

name  |  sum
-------+-------
 Teddy | 20000
 Paul  | 40000
 Mark  | 65000
 Kim   | 45000
 James | 20000
 David | 85000
 Allen | 15000
(7 rows)