简体   繁体   English

SQL中的动态日期范围基于运行查询的时间

[英]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 我觉得我需要用Python来做这件事,但我想先在这里查看

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 我有这些报告是在本月的第一天从Splunk自动生成的,并想知道是否有办法在上个月的整个过程中运行报告而无需设置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. 至少在Oracle中,不确定您使用的是哪个数据库。

Using add_months( trunc(sysdate,'MM'), -1 ) and trunc(sysdate,'MM') resolved my issues. 使用add_months(trunc(sysdate,'MM'), - 1)和trunc(sysdate,'MM')解决了我的问题。

Thank you Vebloud 谢谢Vebloud

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM