简体   繁体   中英

Dynamic Date Range in SQL based on time when query is ran

I have a feeling I am going to need to do this in Python instead, but thought I would check here first

I am running the below query that outputs reports for an account and wanted to know if there was any way to dynamically have the data change based on the month I am running it for.

I have these reports being generated automatically from Splunk on the first of the month, and wanted to know if there was a way to run the reports for the entirety of the previous month without having to set sysdate-30

Below is my query

select 
su.first_name, su.last_name, po.orig_nbr, po.dest_nbr, po.time_date_stamp
from popd_account_activity po
join subscriber su on po.subscriber_id=su.subscriber_id
where time_date_stamp > to_date('02-01-2019 00:00:00', 'mm-dd-yyyy HH24:MI:SS')
and time_date_stamp < to_date('02-28-2019 00:00:00', 'mm-dd-yyyy HH24:MI:SS')
and su.corp_acct_nbr=2004346
order by time_date_stamp asc;

and when I have it run next month on the first of the week, I want it to basically run

select 
su.first_name, su.last_name, po.orig_nbr, po.dest_nbr, po.time_date_stamp
from popd_account_activity po
join subscriber su on po.subscriber_id=su.subscriber_id
where time_date_stamp > to_date('03-01-2019 00:00:00', 'mm-dd-yyyy HH24:MI:SS')
and time_date_stamp < to_date('03-29-2019 00:00:00', 'mm-dd-yyyy HH24:MI:SS')
and su.corp_acct_nbr=2004346
order by time_date_stamp asc;

Without me having to go in and update the date range manually.

you can use trunc and add month, this will allways give you whole previous month

select 
su.first_name, su.last_name, po.orig_nbr, po.dest_nbr, po.time_date_stamp
from popd_account_activity po
join subscriber su on po.subscriber_id=su.subscriber_id
where time_date_stamp > add_months( trunc(sysdate,'MM'), -1 )
and time_date_stamp < trunc(sysdate,'MM')
and su.corp_acct_nbr=2004346
order by time_date_stamp asc;

At least in Oracle, not sure which DB are you using.

Using add_months( trunc(sysdate,'MM'), -1 ) and trunc(sysdate,'MM') resolved my issues.

Thank you Vebloud

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