I am trying to write some queries to group things based on each month in postgresql.
Say we have a table "crimes" which has 2 columns "activity date"(timestamp without time zone) and "zipcode"(character varying(5)), how to query the number of crimes for each month given a zipcode?
eg: table "crimes":
activity date zipcode
2014-11-22 00:52:00 12345
2014-10-22 00:52:00 12345
2014-10-24 00:52:00 12345
2014-12-22 00:52:00 54321
input: given zipcode"12345"
output: return
month count
2014-10 2
2014-11 1
The TIMESTAMP (also known as TIMESTAMP WITHOUT TIME ZONE ) and TIMESTAMPTZ (also known as TIMESTAMP WITH TIME ZONE ) types stored as a 64-bit integer as a microsecond offset since 1970-01-01 in CRDB and as a 64-bit integer microsecond offset since 2000-01-01 in PostgreSQL (by default).
The timestamp datatype allows you to store both date and time. However, it does not have any time zone data.
In PostgreSQL 2 temporal data types namely timestamp and timestamptz where one is without timezone and the later is with timezone respectively, are supported to store Time and Date to a column. Both timestamp and timestamptz uses 8 bytes for storing timestamp values.
The date timestamp also doesn't include timezone information, yet a lot of people use it. Of course, that of itself is not an answer. It's valid to use timestamp and date for any timestamps and dates which are always in the same timezone, or are being stored relative to some known timezone.
Try:
select
extract(year from activity_date) as year,
to_char(activity_date, 'Mon') as month,
count(*) as count
from
crimes
group by
1,extract(month from activity_date);
How to get the month from a timestamp (with/out timezone) in PostgreSQL?
Use the function EXTRACT(field FROM source)
SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 2
Link to documentation: https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With