2017-04-15 35 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; 
相關問題