I enjoy writing my sql like below.
The benefit is that I can re-use code blocks that I use multiple times, and when I fix something, I always only need to fix it in one place.
E.g. I write 2 times current_year instead of extract (year from sys_date).
Other example, I write 2 times first_of_april_this_year instead of to_date ('01.APR.'|| current_year ||' 00:00:00', 'DD.MON.YYYY HH24:MI:SS').
It works, but as you can see below, it's not very pretty / easy to read. Do you have better suggestions where I do not lose the benefit of never having to fix something in multiple places, but make it more readable? I also used with-clauses, but IMHO that's even less readable. Thank you very much! <3
PS: Let's please stay on the topic of re-using code blocks here, and not dig into how this specific task of finding the previous 1st of April in a testable way could have been done better. TY!
-- gives the latest 1st of April based on sysdate, whereas for testing sysdate can freely be set
select
case when sys_date <= first_of_april_this_year then first_of_april_last_year else first_of_april_this_year end previous_first_of_april
-- ,params3.*
from (
select
to_date ('01.APR.'|| current_year ||' 00:00:00', 'DD.MON.YYYY HH24:MI:SS') first_of_april_this_year,
to_date ('01.APR.'||(current_year-1) ||' 00:00:00', 'DD.MON.YYYY HH24:MI:SS') first_of_april_last_year,
params2.*
from (
select
extract (year from sys_date) current_year,
params1.*
from
(select
to_date ('02.AUG.2018 00:00:01', 'DD.MON.YYYY HH24:MI:SS') sys_date -- for testing, sysdate can be overwritten
--sysdate sys_date
from dual) params1
) params2
) params3;