Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

sql - PostgreSQL last full n months

I have a query with dates for the last two years. I want to get data dynamically for the last 4 months. That is if today 04/01/2021 I want to get data from 01/09/2020 up today inclusive. The problem with my query is that I get data between 04/09/2020 up today, i.e. 4 months not including a full first month. PostgreSQL

SELECT     Category,
           Product,
           Sales,
           Date
FROM Table
WHERE Date>= now() - INTERVAL '4 months'

What I need to change in my query ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it using date_trunc like following query.

        SELECT     Category,
           Product,
           Sales,
           Date
FROM Table
WHERE Date>= date_trunc('month', current_date-interval '4 months')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...