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