简体   繁体   中英

Comparing Selected Date Range With Current & Previous Month

I would like to provide the user to option to select a range of date in current month and results should be comparison of same date range for current & previous month. Eg. selected date 1-12-2022 to 15-12-2022 Result:

Count X 1-11-2022 to 15-11-2022
Count X 1-12-200 to 15-12-2022

Can this be achieved through date_part function?

Suppose you have a column with type date named ts in your table:

SELECT
    count(*) FILTER ( WHERE ts BETWEEN cast(:lower AS DATE) - INTERVAL '1 month' AND cast(:upper AS DATE) - INTERVAL '1 month') previous,
    count(*) FILTER ( WHERE ts BETWEEN cast(:lower AS DATE) AND cast(:upper AS DATE) ) selected,
    count(*) FILTER ( WHERE ts BETWEEN cast(:lower AS DATE) + INTERVAL '1 month' AND cast(:upper AS DATE) + INTERVAL '1 month' ) next
FROM your_table;

You just need to provide the lower and upper bound values as dates (eg '01-12-2022'. This will give you 3 columns -- previous , selected and next -- with the corresponding row-counts. BTW: the upper bound is exclusive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM