Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL(postgresql) How to group based on a "timestamp without time zone" column?

Tags:

postgresql

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
like image 395
user3692521 Avatar asked Jan 20 '15 06:01

user3692521


People also ask

What is TIMESTAMP without timezone in PostgreSQL?

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

Is TIMESTAMP stored without timezone?

The timestamp datatype allows you to store both date and time. However, it does not have any time zone data.

How does Postgres store TIMESTAMP with timezone?

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.

Does TIMESTAMP include timezone?

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.


2 Answers

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);
like image 156
Jacob Lambert Avatar answered Sep 27 '22 20:09

Jacob Lambert


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

like image 27
Cornelius Roemer Avatar answered Sep 27 '22 19:09

Cornelius Roemer