Oracle
 sql >> Database >  >> RDS >> Oracle

Previsione di dati di serie temporali in Oracle/SQL

Puoi creare una previsione semplice utilizzando il REGR funzioni di regressione lineare.

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

Di seguito è riportato lo schema di esempio. Oppure puoi usare questo 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;

Il REGR la funzione si occupa di coppie di numeri, non comprende regole aziendali come "il fatturato non può essere inferiore a 0". Se desideri limitare le previsioni a rimanere sempre pari o superiore a 0, un CASE l'espressione può aiutare:

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