0

I'm new to PostgreSQL and I'm wondering if there is a faster/easier way to convert a timestamp to YY or YYYYMM format?

**substring**

select count(1), substring(text(id_timestamp),0,8)  
from dual
where  id_timestamp >= (now()- '3 month'::INTERVAL)
group by substring(text(id_timestamp),0,8) 


**to_char**

select count(1),to_char(id_timestamp,'YYYY-MM') 
from dual
where  id_timestamp >= (now()- '3 month'::INTERVAL)
group by to_char(id_timestamp,'YYYY-MM') 

Year:

select count(1),to_char(id_timestamp,'YYYY') 
from dual
where  id_timestamp >= (now()- '3 month'::INTERVAL)
group by to_char(id_timestamp,'YYYY') 

1 Answer 1

1

to_char is how you do it. To not have to repeat the expressions in the select list it is possible to refer to them by their position in the list:

select count(*), to_char(id_timestamp,'YYYY-MM') 
from t
group by 2
order by 2

There is no dual in Postgresql.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.