SQL中的动态日期范围(根据查询运行的时间)

时间:2019-03-20 16:10:05

标签: sql oracle

我有一种感觉,我需要用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;

无需我手动输入和更新日期范围。

2 个答案:

答案 0 :(得分:0)

您可以使用trunc并添加月份,这将始终为您提供整个上个月的信息

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中,不确定您使用的是哪个数据库。

答案 1 :(得分:0)

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

谢谢Vebloud