sql - 在 Oracle/SQL 中预测时间序列数据

标签 sql oracle

有没有一种方法可以使用 Oracle 分析函数为数据集生成时间序列预测?我们如何在 SQL/ORACLE 中执行外推。

下面是我的需要

我有如下数据集,我想预测/推断明年

Cust_id  Year  Revnue
1        2016  679862
1        2017  705365
1        2018  ?
2        2016  51074
2        2017  50611
2        2018  ?
3        2016  190706
3        2017  90393
3        2018  ?
4        2016  31649
4        2017  19566
4        2018  ?

最佳答案

您可以使用 REGR 创建一个简单的预测。线性回归函数。

--Ordinary least squares forecast for each customer for the next year.
select
    cust_id,
    max(year) +1 forecast_year,
    -- y = mx+b
    regr_slope(revenue, year)
        * (max(year) + 1)
        + regr_intercept(revenue, year) forecasted_revenue
from customer_data
group by cust_id;

CUST_ID   FORECAST_YEAR   FORECASTED_REVENUE
-------   -------------   ------------------
1                  2018               730868
2                  2018                50148
4                  2018                 7483
3                  2018                -9920

下面是示例架构。或者您可以使用 this SQLFiddle .
create table customer_data
(
    cust_id number,
    year number,
    revenue number
);

insert into customer_data
select 1, 2016, 679862 from dual union all
select 1, 2017, 705365 from dual union all
select 2, 2016, 51074  from dual union all
select 2, 2017, 50611  from dual union all
select 3, 2016, 190706 from dual union all
select 3, 2017, 90393  from dual union all
select 4, 2016, 31649  from dual union all
select 4, 2017, 19566  from dual;
REGR函数处理数字对,它不理解“收入不能低于 0”等业务规则。如果您想将预测限制为始终保持在 0 或以上,则 CASE表达可能有帮助:
--Forecasted revenue, with minimum forecast of 0.
select cust_id, forecast_year,
    case when forecasted_revenue < 0 then 0 else forecasted_revenue end forecasted_revenue
from
(
    --Ordinary least squares forecast for each customer for the next year.
    select
        cust_id,
        max(year) +1 forecast_year,
        -- y = mx+b
        regr_slope(revenue, year)
            * (max(year) + 1)
            + regr_intercept(revenue, year) forecasted_revenue
    from customer_data
    group by cust_id
);

CUST_ID   FORECAST_YEAR   FORECASTED_REVENUE
-------   -------------   ------------------
1                  2018               730868
2                  2018                50148
4                  2018                 7483
3                  2018                    0

关于sql - 在 Oracle/SQL 中预测时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55134697/

相关文章:

java - Oracle PreparedStatement - 一些开发人员的 NullPointerException,但不是全部

sql - 具有基于主键的日志的快速刷新物化 View

c# - Oracle ODP.NET 托管驱动程序在 64 位中的运行速度比在 32 位中慢 50-100%

PHP:无法让 Oracle 表显示在页面上

java - 使用 HSQL 请求父实体时过滤一对多子实体

oracle - 选择数字范围不重叠的地方

sql - 查找约束中的父键

sql - 有自定义年份,而不是日历年

MySQL 按第一个表中匹配的行排序,然后休息

sql - 为什么我的 Access 2007 查询突然变得不可更新?