Languages
[Edit]
EN

Node.js - PostgreSQL- group rows by months

0 points
Created by:
leila
435

In this article, we would like to show you how to group rows by months in the Postgres database from Node.js level.

Node.js - PostgreSQL- group rows by months
Table used in the example - HeidiSQL

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('month', "event_timestamp") AS "month",
                COUNT(*)
            FROM "events"
            GROUP BY DATE_TRUNC('month', "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) β”‚         month         β”‚ count β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚ '2021-03-01 00:00:00' β”‚  '5'  β”‚
β”‚    1    β”‚ '2021-04-01 00:00:00' β”‚  '7'  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

Note:

In the example above, the month column shows the date 1 day back (time zone-adjusted conversion), check the example below, which may be clearer for you.

Another solution

const { Client } = require('pg');

const client = new Client({
    host: '127.0.0.1',
    user: 'my_username',
    database: 'my_database',
    password: 'my_password',
    port: 5432,
});

const fetchEventsGroupedByMonths = async () => {
	const query = `    
            SELECT 
                TO_CHAR(event_timestamp,'month') AS "month",
                EXTRACT(YEAR FROM event_timestamp) AS "year",
                COUNT(*)
            FROM "events"
            GROUP BY TO_CHAR(event_timestamp,'month'), EXTRACT(YEAR FROM event_timestamp) // or GROUP BY 1,2
    `;
    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) β”‚    month    β”‚ year β”‚ count β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚ 'march    ' β”‚ 2021 β”‚  '5'  β”‚
β”‚    1    β”‚ 'april    ' β”‚ 2021 β”‚  '7'  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

Database preparation

create_tables.sqlΒ file:

CREATE TABLE "events" (
	"id" SERIAL PRIMARY KEY,
	"event_timestamp" TIMESTAMP NOT NULL
);

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):

Example 1:

SELECT
     DATE_TRUNC('month', "event_timestamp") AS "month",
     COUNT(*)
 FROM "events"
 GROUP BY DATE_TRUNC('month', "event_timestamp")

Example 2:

SELECT 
    TO_CHAR(event_timestamp,'month') AS "month",
    EXTRACT(YEAR FROM event_timestamp) AS "year",
    COUNT(*)
FROM "events"
GROUP BY TO_CHAR(event_timestamp,'month'), EXTRACT(YEAR FROM event_timestamp) // or GROUP BY 1,2
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - PostgreSQL - dates

Native Advertising
πŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

β€οΈπŸ’» πŸ™‚

Join