Languages
[Edit]
EN

PostgreSQL - Group rows by weeks

0 points
Created by:
Explosssive
559

In this article, we would like to show you how in the group rows by weeks in PostgreSQL.

PostgreSQL - Group rows by weeks
Table used in the example - HeidiSQL

Note: at the end of this article you can find database preparation SQL queries.

SQL example:

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

Result:

PostgreSQL - Group rows by weeks
Results - HeidiSQL

Shorter notation of the example above:

SELECT
    DATE_TRUNC('week', "event_timestamp") AS "week",
    COUNT(*)
FROM "events"
GROUP BY 1
ORDER BY 1

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');

Alternative titles

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.

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