sql - get previous week date in select query -
i have below query using reporting in cognos. doing reporting every week on monday previous week monday till sunday.
currently date hardcoded want make dynamic everytime when run report on monday dont have change date previous week.
is possible can make day_date dynamic using sysdate in select query ?
select id,name,day_date test_report day_date between to_date ('20170904', 'yyyymmdd') , to_date ('20170910', 'yyyymmdd');
you can calculate start , end dates of previous week current date using trunc (date) function.
let running query on monday 2017-09-11, on friday 2017-09-15, , query must generate report previous week.
query calculates start date of current week:
select trunc( date '2017-09-11', 'iw' ) x, trunc( date '2017-09-15', 'iw' ) y dual; x y ---------------- ---------------- 2017/09/11 00:00 2017/09/11 00:00 to calculate start date of previous week, substract 1 day above dates, , use truct again:
select trunc( trunc( date '2017-09-11', 'iw' ) - 1, 'iw') start_last_week, trunc( trunc( date '2017-09-15', 'iw' ) - 1, 'iw') start_last_week1 dual; start_last_week start_last_week1 ---------------- ---------------- 2017/09/04 00:00 2017/09/04 00:00 so, in query use clause (date >= start of previous week , < start of current week):
where day_date>= trunc( trunc( sysdate, 'iw' ) - 1, 'iw') , day_date < trunc( sysdate, 'iw' )
Comments
Post a Comment