使用SQL计算CAGR

时间:2018-03-20 22:17:31

标签: sql

我有一个如下所示的数据集

ADVERTISER       YR     REVENUE
---------------------------------
Altus Dental    2015    5560.00
Altus Dental    2016    48295.00
Altus Dental    2017    39920.00

我正在努力寻找年复合增长率并取其平均值,这意味着

CAGR = (((REVENUE(2016)/REVENUE(2015)) - 1) + ((REVENUE(2017)/REVENUE(2016)) - 1) ) / 2

最后我需要一个像这样的输出

ADVERTISER      CAGR
--------------------
Altus Dental    3.75

如何在SQL中完成此操作?请帮我为此提供有效的解决方案。

3 个答案:

答案 0 :(得分:1)

计算每年的CAGR(收入/ prev_revenue - 1)并计算平均CAGR(假设您的dbms支持LAG函数)

select advertiser, avg(cagr) as CAGR
from
(
select advertiser, yr, revenue, revenue/prev_revenue - 1 as cagr
from
   (select *, lag(revenue, 1) over 
              (partition by advertiser order by yr) as prev_revenue
    from test ) t
) t1
group by advertiser

答案 1 :(得分:0)

这是一种方式:

select advertiser,
       (((t16.revenue/t15.revenue) - 1) + ((t17.revenue/t16.revenue) - 1) ) / 2 as cagr
from t t15 join
     t t16
     on t15.advertiser = t16.advertiser and t15.yr = 2015 and t16.yr = 2016 join
     t t17
     on t15.advertiser = t17.advertiser and t17.yr = 2017

答案 2 :(得分:0)

我假设年份列表中不会出现“漏洞”。这应该适用于n年,n广告客户:

SELECT advertiser,
       SUM(revenue) / (COUNT(*) - 1) AS CAGR
  FROM (SELECT advertiser,
               COALESCE((revenue/revenue_old - 1), 0) as revenue
          FROM (SELECT s.advertiser,
                       s.revenue,
                       LAG(s.revenue, 1) OVER(PARTITION BY s.advertiser
                                                  ORDER BY s.yr) AS revenue_old
                  FROM table_1 s))
 GROUP BY advertiser;