EN
PostgreSQL - GROUP BY multiple columns
0
points
In this article, we would like to show you how to use GROUP BY statement with multiple columns in PostgreSQL.
Quick solution:
SELECT "column1", "column2", "columnN"
FROM "table_name"
WHERE condition
GROUP BY "column1", "column2", "columnN"
ORDER BY "column_name";
Practical example
To show how GROUP BY with multiple columns works, we will use the following table:
Note:
At the end of this article you can find database preparation SQL queries.
Example
In this example, we will display the number of users with the same name and department_id.
Query:
SELECT "name", "department_id", COUNT(*)
FROM "users"
GROUP BY "name","department_id";
Result:
Result explanation:
As we see, the COUNT(*) column contains the number of users with the same name and department_id. For example, there are three people named Ailisa in the department 3.
Database preparation
create_tables.sql file:
CREATE TABLE "users" (
"id" SERIAL,
"name" VARCHAR(50) NOT NULL,
"surname" VARCHAR(50) NOT NULL,
"department_id" INTEGER,
"salary" DECIMAL(15,2) NOT NULL,
PRIMARY KEY ("id")
);
insert_data.sql file:
INSERT INTO "users"
( "name", "surname", "department_id", "salary")
VALUES
('John', 'Stewart', 1, '2000.00'),
('Chris', 'Brown', 3, '2000.00'),
('Chris', 'Lewis', 3, '2000.00'),
('Kate', 'Lewis', 3, '2000.00'),
('Kate', 'Stewart', 3, '2000.00'),
('Ailisa', 'Lewis', 3, '2000.00'),
('Ailisa', 'Gomez', 3, '3000.00'),
('Gwendolyn', 'James', 2, '3000.00'),
('Simon', 'James', 2, '2000.00'),
('Simon', 'Brown', 3, '2000.00'),
('Simon', 'Collins', 3, '3000.00');