I'm not much experienced with Oracle SQL and been trying to accomplish some task for which I intend to use
select count(*) from TABLE where date = (select trunc(sysdate -1 ) from dual)
The above query gives me the result for all the records with sysdate minus 1. I want to automate it to handle the scenario of Sat and Sunday and modify the query to something like below
select count(*) from TABLE where date = (select trunc(sysdate -@var ) from dual)
where @var = 2 if the query runs on Sunday and @var = 3 if the query is running on Monday
TRUNC( SYSDATE, 'IW' )
will truncate the date to the start of the ISO week - so midnight Monday. TRUNC( SYSDATE ) - TRUNC( SYSDATE, 'IW' )
will give the number of full days since the start of the ISO week (Monday = 0, Tuesday = 1, ... Sunday = 6) and you can just put that into a CASE
statement:
select count(*)
from your_table
where date_col = TRUNC(SYSDATE) - CASE TRUNC(SYSDATE) - TRUNC(SYSDATE, 'IW')
WHEN 0 THEN 3 -- Monday
WHEN 6 THEN 2 -- Sunday
ELSE 1 -- Other days
END
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.