简体   繁体   中英

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

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, eg:

1238 on Monday
3487 on Tuesday
1237 on Wednesday

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM