EN
Node.js - PostgreSQL Group rows by days
0
points
In this article, we would like to show you howΒ in the group rows by daysΒ inΒ PostgresΒ database from Node.js level.
Note:Β at the end of this article you can find database preparation SQL queries.
const pg = require('pg');
const types = pg.types;
types.setTypeParser(1114, (stringValue) => {
return stringValue;
});
const client = new pg.Client({
host: '127.0.0.1',
user: 'my_username',
database: 'my_database',
password: 'my_password',
port: 5432,
});
const fetchEventsGroupedByMonths = async () => {
const query = `
SELECT
DATE_TRUNC('day', "event_timestamp") AS "day",
COUNT(*)
FROM "events"
GROUP BY DATE_TRUNC('day', "event_timestamp")
ORDER BY DATE_TRUNC('day', "event_timestamp")
`;
await client.connect(); // creates connection
try {
const { rows } = await client.query(query); // sends query
return rows;
} finally {
await client.end(); // closes connection
}
};
fetchEventsGroupedByMonths()
.then(result => console.table(result))
.catch(error => console.error(error.stack));
Result:Β
βββββββββββ¬ββββββββββββββββββββββββ¬ββββββββ
β (index) β day β count β
βββββββββββΌββββββββββββββββββββββββΌββββββββ€
β 0 β '2021-03-11 00:00:00' β '1' β
β 1 β '2021-03-21 00:00:00' β '1' β
β 2 β '2021-03-22 00:00:00' β '2' β
β 3 β '2021-03-23 00:00:00' β '1' β
β 4 β '2021-04-05 00:00:00' β '2' β
β 5 β '2021-04-16 00:00:00' β '1' β
β 6 β '2021-04-17 00:00:00' β '1' β
β 7 β '2021-04-23 00:00:00' β '3' β
βββββββββββ΄ββββββββββββββββββββββββ΄ββββββββ
Database preparation
create_tables.sql
Β file:
CREATE TABLE "events" (
"id" SERIAL NOT NULL,
"event_timestamp" TIMESTAMP NOT NULL,
PRIMARY KEY ("id")
);
insert_data.sql
Β file:
INSERT INTO "events"
("event_timestamp")
VALUES
('2021-03-11 11:41:31'),
('2021-03-21 12:42:32'),
('2021-03-22 14:44:34'),
('2021-03-22 15:45:35'),
('2021-03-23 16:46:36'),
('2021-04-05 17:47:37'),
('2021-04-05 19:49:39'),
('2021-04-16 20:50:40'),
('2021-04-17 15:45:35'),
('2021-04-23 16:46:36'),
('2021-04-23 19:49:39'),
('2021-04-23 20:50:40');
Native SQL query (used in the above example):
SELECT
DATE_TRUNC('day', "event_timestamp") AS "day",
COUNT(*)
FROM "events"
GROUP BY DATE_TRUNC('day', "event_timestamp")
ORDER BY DATE_TRUNC('day', "event_timestamp")