跨行计算比上期
【问题】
Hello All, can anyone help me in creating query(groupby) to find total revenue by year and YoY change %...For example I have data as
revenue Date
616.0984 2001-07-08 00:00:00.000
38.8276 2001-07-15 00:00:00.000
985.553 2002-07-08 00:00:00.000
867.2389 2002-07-08 00:00:00.000
12.5838 2002-07-15 00:00:00.000
732.81 2003-02-08 00:00:00.000
429.9821 2003-01-01 00:00:00.000
151.9921 2003-07-08 00:00:00.000
183.1626 2003-07-08 00:00:00.000
Required Result:
Year - Total - YoY
2001 - -
2002 - -
2003 - -
【回答】
这是个典型的行间计算,使用SQL的窗口函数可以实现行间计算,但是窗口函数比较抽象,再加上和分组汇总要混在一起用,代码就比较难写了。如果数据量不是很大,SPL实现比较简单直观,脚本如下:
A |
|
1 |
$select * from data |
2 |
=A1.groups(year(Date):Year;sum(revenue):Total) |
3 |
=A2.derive((Total-Total[-1])/Total[-1]:YoY) |
A1:sql取数
A2:按照year(Date)累计分组汇总revenue
A3:在A2基础上增加YoY%列,列值由(total-total[-1])/total[-1]计算得到
写好的脚本如何在应用程序中调用,可以参考Java 如何调用 SPL 脚本