简体   繁体   中英

Finding the last date of the previous quarter from current date in PostGreSQL

For example: If my current date is 2022-07-21, my query should give me 2022-06-30. I could easily do it in IBM DB2 but struggling in postgresql.

You can truncate the current date to its quarter, then remove 1 day from that (and potentially cast back to date):

-- You really only need the last column, the other two just show the different steps in the process
SELECT DATE_TRUNC('quarter', CURRENT_DATE)
     , DATE_TRUNC('quarter', CURRENT_DATE) - '1 day'::INTERVAL
     , (DATE_TRUNC('quarter', CURRENT_DATE) - '1 day'::INTERVAL)::DATE

outputs

+---------------------------------+---------------------------------+----------+
|date_trunc                       |?column?                         |date      |
+---------------------------------+---------------------------------+----------+
|2022-07-01 00:00:00.000000 +00:00|2022-06-30 00:00:00.000000 +00:00|2022-06-30|
+---------------------------------+---------------------------------+----------+

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-2025 STACKOOM.COM