I want to create a query that, when it is run on Monday, it retrieves data from Friday. When it is another weekday, it should retrieve data of previous day. At the moment I created this query, which works perfectly except on Monday:
Select sum(od.shippedqty) as SHIPPEDQTY
from orderdetail od, orders o
Where o.orderkey = od.orderkey
and to_char(o.actualshipdate, 'YYYYMMDD') = to_char(sysdate, 'YYYYMMDD') -1
I have tried to do something with a case function and all kind of tips found on the web, but I did not manage to get it to work. Who can help me.
If this query works OK for you, just change the -1
at the very end with
- case to_char(sysdate, 'Dy') when 'Mon' then 3 else 1 end
With that said - how are you subtracting 1 from a string? Oracle will convert that string back to a number for you, but that is not going to work correctly as dates.
Rather:
... and o.actualshipdate >= trunc(sysdate) - <expression from above>
and o.actualshipdate < trunc(sysdate) - <expression from above> + 1
This is better than using trunc
on the left-hand side and comparing to trunc(sysdate)
, because it allows the use of an index on actualshipdate
(assuming there is one, as there should be if you run queries similar to this one often).
Edit : See MT0's comment below (thank you, MT0!). Of course, he is right; if the query may be used in non-English speaking locales, that may be a problem. Even with my suggested modification to the where
clause, there is still a to_char()
in the whole thing - in the case
expression. That should be written as:
to_char(sysdate, 'Dy', 'nls_date_language = English')
You can use:
CASE TRUNC( your_date ) - TRUNC( your_date, 'IW' )
WHEN 0 THEN your_date - INTERVAL '3' DAY -- Monday
WHEN 6 THEN your_date - INTERVAL '2' DAY -- Sunday
ELSE your_date - INTERVAL '1' DAY -- Tuesday - Saturday
END AS previous_workday
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.