Jon
Jon

Reputation: 109

How to calculate range in 1 week using Postgres?

tanggal    | product
2021-01-01   bag 1
2021-01-05   bag 5
2021-01-08   bag 8
2021-01-11   bag 11
2021-01-12   bag 12
2021-01-13   bag 13
2021-01-14   bag 14

here I have a product tbl, in this table there are input dates and product names, I want to calculate the product based on 1 week how the query to calculate the data with a range of 7 days?

and this my query

select tanggal, product from tbl_product
where tanggal > current_date + interval '7' day

Upvotes: 0

Views: 165

Answers (1)

filpa
filpa

Reputation: 3654

You could solve this for arbitrary dates using a generated time series.

For example:

SELECT series::date 
FROM generate_series(
        (now() - interval '1 week')::date,
        now()::date,
        '1 day'::interval
) series;

Would result in:

2021-05-26
2021-05-27
2021-05-28
2021-05-29
2021-05-30
2021-05-31
2021-06-01
2021-06-02

which you can join with other tables as you see fit.

For further information on generate_series() and other set-returning functions, check out the documentation.

Upvotes: 1

Related Questions