W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在 PostgreSQL 中,GROUP BY 語句和 SELECT 語句一起使用,用來對相同的數(shù)據(jù)進(jìn)行分組。
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 子句中,你可以對一列或者多列進(jìn)行分組,但是被分組的列必須存在于列清單中。
創(chuàng)建 COMPANY 表 ,數(shù)據(jù)內(nèi)容如下:
w3cschooldb# 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)
下面實例將根據(jù) NAME 字段值進(jìn)行分組,找出每個人的工資總額:
w3cschooldb=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;
得到以下結(jié)果:
name | sum -------+------- Teddy | 20000 Paul | 20000 Mark | 65000 David | 85000 Allen | 15000 Kim | 45000 James | 10000 (7 rows)
現(xiàn)在我們添加使用下面語句在 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);
現(xiàn)在 COMPANY 表中存在重復(fù)的名稱,數(shù)據(jù)如下:
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)
現(xiàn)在再根據(jù) NAME 字段值進(jìn)行分組,找出每個客戶的工資總額:
w3cschooldb=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;
這時的得到的結(jié)果如下:
name | sum -------+------- Allen | 15000 David | 85000 James | 20000 Kim | 45000 Mark | 65000 Paul | 40000 Teddy | 20000 (7 rows)
下面實例將 ORDER BY 子句與 GROUP BY 子句一起使用:
w3cschooldb=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;
得到以下結(jié)果:
name | sum -------+------- Teddy | 20000 Paul | 40000 Mark | 65000 Kim | 45000 James | 20000 David | 85000 Allen | 15000 (7 rows)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: