窗口函数 - 日期之间的范围
Posted
技术标签:
【中文标题】窗口函数 - 日期之间的范围【英文标题】:Window Function - Range Between Dates 【发布时间】:2015-02-20 14:56:48 【问题描述】:我收到错误消息,我的代码 (Oracle) 中缺少关键字。我的想法是创建一个 as/was 的支出 last3,6,12 视图。因此,我想知道 jan14 的 last3 花费是多少,最后 3 个月中包含的月份是:Oct13、Nov13、Dec14。
使用合并到 account_month_tb (选择 account_month_tb.acct_id、account_month_tb.month_start_dt,
--rolling spend buckets
sum(spend) over
(partition by account_month_tb.acct_id order by account_month_tb.month_start_dt
range between interval '3' month preceding and preceding month) as spend_last3,
sum(spend) over
(partition by account_month_tb.acct_id order by account_month_tb.month_start_dt
range between interval '6' month preceding and preceding month) as spend_last6,
sum(spend) over
(partition by account_month_tb.acct_id order by account_month_tb.month_start_dt
range between interval '12' month preceding and preceding month) as spend_last12
--mkdn buckets
from account_month_tb
) rolling_14
on (account_month_tb.acct_id = rolling_14.acct_id and
account_month_tb.month_start_dt = rolling_14.month_start_dt)
when matched then update set
account_month_tb.spend_last3 = rolling_14.spend_last3,
account_month_tb.spend_last6 = rolling_14.spend_last6,
account_month_tb.spend_last12 = rolling_14.spend_last12
;
commit;
错误信息:
命令行错误:163 列:62 错误报告 - SQL 错误:ORA-00905:缺少关键字 00905. 00000 - “缺少关键字” *原因: *行动: 承诺。
【问题讨论】:
也许显示您正在执行的整个语句以及完整的错误消息会有所帮助?如果这是一种观点,你似乎在发明新的语法。 为什么会被否决? 所以and preceding month
应该是and interval '1' month preceding
?
【参考方案1】:
在windowing clause 中,preceding month
没有任何意义且无效。你的意思似乎是interval '1' month preceding
。
在 CTE 中使用一些虚拟数据进行模拟:
with account_month_tb as (
select 1 as acct_id,
trunc(sysdate - (16 * level), 'MM') as month_start_dt,
level as spend
from dual
connect by level < 10
)
select account_month_tb.acct_id, account_month_tb.month_start_dt,
sum(spend) over (partition by account_month_tb.acct_id
order by account_month_tb.month_start_dt
range between interval '3' month preceding
and interval '1' month preceding) as spend_last3
from account_month_tb;
ACCT_ID MONTH_START_DT SPEND_LAST3
---------- -------------- -----------
1 01-09-2014
1 01-10-2014 9
1 01-10-2014 9
1 01-11-2014 24
1 01-12-2014 30
1 01-12-2014 30
1 01-01-2015 30
1 01-01-2015 30
1 01-02-2015 20
SQL Fiddle 包含三个总和和更多数据。但是,您会得到很多重复,这可能不是您想要的。也许you just need distinct values。
【讨论】:
以上是关于窗口函数 - 日期之间的范围的主要内容,如果未能解决你的问题,请参考以下文章