EN
Node.js - PostgreSQL - GROUP BY multiple columns
0
points
In this article, we would like to show you how to GROUP BY multiple columns in the PostgreSQL database using Node.js.
Note: at the end of this article you can find database preparation SQL queries.
const { Client } = require('pg');
const client = new Client({
host: '127.0.0.1',
user: 'postgres',
database: 'database_name',
password: 'password',
port: 5432,
});
const fetchUsers = async () => {
const query = `SELECT "name", "department_id", COUNT(*)
FROM "users"
GROUP BY "name","department_id"
ORDER BY "name";`;
try {
await client.connect(); // gets connection
const { rows } = await client.query(query); // sends query
console.table(rows);
} catch (error) {
console.error(error.stack);
} finally {
await client.end(); // closes connection
}
};
fetchUsers();
Result:
┌─────────┬─────────────┬───────────────┬───────┐
│ (index) │ name │ department_id │ count │
├─────────┼─────────────┼───────────────┼───────┤
│ 0 │ 'Ailisa' │ 3 │ '2' │
│ 1 │ 'Chris' │ 3 │ '2' │
│ 2 │ 'Gwendolyn' │ 2 │ '1' │
│ 3 │ 'John' │ 1 │ '1' │
│ 4 │ 'Kate' │ 3 │ '2' │
│ 5 │ 'Simon' │ 3 │ '2' │
│ 6 │ 'Simon' │ 2 │ '1' │
└─────────┴─────────────┴───────────────┴───────┘
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');
Native SQL query (used in the above example):
SELECT "name", "department_id", COUNT(*)
FROM "users"
GROUP BY "name","department_id"
ORDER BY "name"