How many records created for each day of the week this year?

83 views Asked by At

I have about 50k rows in a Postgres database that are users and when they signed up.

I am trying to understand how many users sign up for each day of the week since the start of the year, e.g.:

1238 on Monday
3487 on Tuesday
1237 on Wednesday

Example date entry: '2014-10-31 17:17:30.138579'

2

There are 2 answers

0
CoryatJohn On

You can use the EXTRACT(DOW from timestamp) to determined the day of the week. 0 is Sunday. 6 is Saturday.

Example:

SELECT EXTRACT(DOW FROM TIMESTAMP '2015-06-22 20:38:40');

Result is 1 (Monday)

0
Erwin Brandstetter On

A plain aggregate query after extracting the weekday. You could use to_char() to get the (English by default) weekday:

SELECT to_char(created_at, 'Day'), count(*) AS ct
FROM   tbl
WHERE  created_at >= date_trunc('year', now())
GROUP  BY 1;

If performance is important, EXTRACT() is slightly faster:

SELECT EXTRACT(ISODOW FROM created_at), count(*) AS ct
FROM   tbl
WHERE  created_at >= date_trunc('year', now())
GROUP  BY 1;

1 .. Monday, ... , 7 .. Sunday.