在Snowflake SQL中计算通货膨胀率

huangapple go评论66阅读模式
英文:

Calculate Inflation rates in Snowflake SQL

问题

在Snowflake SQL中,我有一个包含年度通货膨胀率的表,如下所示:

年份 通货膨胀率
2000 1.1 %
2001 1.3 %
2002 -1.3 %
2003 2.3 %

我想要创建一个表,其中对于每一年,显示相对于基准年2000的总通货膨胀率。

谢谢!

英文:

In snowflake SQL, I have a table with inflation factors, year on year, like this:

Year Inflation
2000 1.1 %
2001 1.3 %
2002 -1.3 %
2003 2.3 %

I want to produce a table with, for every year, the total inflation from base year 2000

Thanks!

There is an old, similar question here, but I can't figure out how to adapt it

*** UPDATE ***

I tried the suggested solution, but it doesn't work:

在Snowflake SQL中计算通货膨胀率

答案1

得分: 1

你可以使用SQL 窗口函数,以及一些算术技巧来实现这个目标。简而言之,结合SUM()LOG()EXP()函数来获得你想要的结果。

这个想法背后的算术技巧是
A X B = EXP(LOG(EXP(1),A)+LOG(EXP(1),B))

我们使用基于窗口的sum()函数来计算截止到年份X的累积对数(通货膨胀率)值,然后应用exp()来获得原始的累积通货膨胀率。

看下面的示例代码(在Snowflake SQL语法中,代码中使用了Snowflake特定的ln()函数):

select 
   record_year, 
   inflation_rate, 
   round(exp(SUM(ln(1+inflation_rate)) OVER (ORDER BY record_year)) -1,3)  as cum_inflation_rate
FROM inflation_data

验证运行示例 SQLFIDDLE 链接

示例输出:

record_year inflation_rate cum_inflation_rate
2000 0.011 0.011
2001 0.013 0.024
2002 -0.013 0.011
2003 0.023 0.034
英文:

You can use SQL Window Function, and some arithmetic trick to do that.In short, combine SUM(), LOG() and EXP() functions to get the result you wants.

The arithmetic trick behind the idea is
A X B = EXP(LOG(EXP(1),A)+LOG(EXP(1),B))

We use window-based sum() function to calculate the cumulative log(inflation rate) value up to year X. and then apply exp() to get raw cumulative inflation rate.

See the following code as example(in snowflake sql syntax, use snowflake-specific ln() function in the code):

select 
   record_year, 
   inflation_rate, 
   round(exp(SUM(ln(1+inflation_rate)) OVER (ORDER BY record_year)) -1,3)  as cum_inflation_rate
FROM inflation_data

VERIFIED RUNNING EXAMPLE SQLFIDDLE LINK

example output:

record_year inflation_rate cum_inflation_rate
2000 0.011 0.011
2001 0.013 0.024
2002 -0.013 0.011
2003 0.023 0.034

huangapple
  • 本文由 发表于 2023年2月24日 01:11:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定