簡體   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