📅  最后修改于: 2023-12-03 15:01:04.949000             🧑  作者: Mango
In SQL, the GROUP BY clause is used to group the result set based on one or more columns. PostgreSQL also allows the use of GROUP BY clause to group data together based on one or more columns.
The basic syntax of using GROUP BY in PostgreSQL is as follows:
SELECT column1, column2, ... FROM table_name GROUP BY column_name1, column_name2, ...;
Consider the following table employees
:
| id | name | age | department | |----|------|-----|------------| | 1 | John | 23 | Sales | | 2 | Jane | 32 | IT | | 3 | Mark | 27 | HR | | 4 | Adam | 29 | IT | | 5 | Anna | 21 | Sales | | 6 | Bill | 25 | HR |
If we group the employees
table based on their department, the SQL query would be:
SELECT department, COUNT(*) as num_employees FROM employees GROUP BY department;
The above query will result in:
| department | num_employees | |------------|--------------| | HR | 2 | | IT | 2 | | Sales | 2 |
The COUNT(*)
function will count the number of rows with a unique department value and assign it to the num_employees
column.
The GROUP BY clause is a useful tool for aggregating data in SQL, and PostgreSQL offers a flexible and powerful implementation of it. By using GROUP BY, we can easily analyze data and extract valuable insights for decision making.