2017-04-15 62 views
0

我计算使用下列公式两个时间范围(5年)之间的增长率获取最新的每个外键的一年,至少最近一年计算

growth rate = ((2016 net income/2012 net income) * 1/(5 years)) - 1 

IncomeStatements表是某种结构是这样的:

id | stockid | year | netincome 
1 | 1  | 2016 | 235235346 
2 | 1  | 2015 | 432434545 
..2014-2013 rows 
5 | 1  | 2012 | 324324234 
6 | 2  | 2016 | 234235234 
7 | 2  | cycle continues.. 

我怎样才能选择最近大多数过去的年(2016年和2012年)每个库存号(FOREIGN KEY)应用公式,然后在stock表中的growthrate列中更新结果?

以下是我的不完整代码。由于我是SQL新手,请帮助我改进或提供解决方法。

UPDATE stock SET growthrate = (Help) 
FROM IncomeStatements WHERE IncomeStatements.stockid= stock.id 
+0

MySQL或SQL服务器? – TriV

+0

sql-server 2014 :) – JPaulPunzalan

回答

1

如果我理解正确,您需要获取年度和净收入的第一个和最后一个值。你可以用窗口函数来做到这一点。

剩下的只是算术:

with i as (
     select distinct stockid, 
      first_value(year) over (partition by stockid order by year) as year_first, 
      first_value(year) over (partition by stockid order by year desc) as year_last, 
      first_value(netincome) over (partition by stockid order by year) as netincome_first, 
      first_value(netincome) over (partition by stockid order by year desc) as netincome_last 
     from incomestatements i 

update s 
    set growthrate = ((i.netincome_last - i.netincome_first)/nullif(i.year_last - i.year_first, 0)) - 1 
    from stock s 
     i 
     on s.stock_id = i.stock_id;