繁体   English   中英

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

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

我觉得我需要用Python来做这件事,但我想先在这里查看

我正在运行以下查询,为帐户输出报告,并想知道是否有任何方法可以根据我运行它的月份动态地更改数据。

我有这些报告是在本月的第一天从Splunk自动生成的,并想知道是否有办法在上个月的整个过程中运行报告而无需设置sysdate-30

以下是我的查询

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;

当我在下个月的第一周运行它时,我希望它基本上运行

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;

没有我必须手动更新日期范围。

你可以使用截断和添加月份,这将总是给你整个上个月

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;

至少在Oracle中,不确定您使用的是哪个数据库。

使用add_months(trunc(sysdate,'MM'), - 1)和trunc(sysdate,'MM')解决了我的问题。

谢谢Vebloud

暂无
暂无

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

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