计算列

时间:2017-08-24 10:52:00

标签: sql-server average moving-average variance

我有下表:

Fruit|  date    |  profit | Rolling_Avg
Apple|2014-01-16|   5.61  | 0.80
Apple|2014-01-17|   3.12  | 1.25
Apple|2014-01-18|   2.20  | 1.56
Apple|2014-01-19|   3.28  | 2.03
Apple|2014-01-20|   7.59  | 3.11
Apple|2014-01-21|   3.72  | 3.65
Apple|2014-01-22|   1.11  | 3.80
Apple|2014-01-23|   5.07  | 3.73

我要做的是按日期以1为增量计算方差,例如返回的表格如下:

Fruit|  date    |  profit | Rolling_Avg| Variance %
Apple|2014-01-16|   5.61  | 0.80       |  
Apple|2014-01-17|   3.12  | 1.25       |-0.443850267
Apple|2014-01-18|   2.20  | 1.56       |-0.294871795
Apple|2014-01-19|   3.28  | 2.03       | 0.490909091
Apple|2014-01-20|   7.59  | 3.11       | 1.31402439
Apple|2014-01-21|   3.72  | 3.65       |-0.509881423
Apple|2014-01-22|   1.11  | 3.80       |-0.701612903
Apple|2014-01-23|   5.07  | 3.73       | 3.567567568

我不知道该怎么做。

我想如果日期是标题而不是行,则更容易将方差%计算为

sum(([2014-01-17] - [2014-01-16])/[2014-01-16])) as [variance %]

但又不完全确定这是最有效的方法

3 个答案:

答案 0 :(得分:1)

您没有计算"方差" - 统计中有一个特定的定义 - 但是"差异"。为此,请使用lag()

select t.*,
       (rolling_avg - 
        lag(rolling_avg) over (order by date)
       ) as diff
from t;

我会做出差异,因为"最近" - "之前"。你似乎正在走另一条路,所以只需颠倒操作数的顺序。

答案 1 :(得分:1)

您可以尝试使用LAG

以下是可能为您提供所需结果的查询。

<强>查询

select fruit,vdate,profit,rolling_avg,
    LAG(profit,1,0) over(order by day(vdate)) as previousprofit,
    ((profit-LAG(profit) over(order by day(vdate)))/LAG(profit) over(order by day(vdate))) as variance_percent
from variance

Fiddle

答案 2 :(得分:0)

如果您使用的是SQL Server 2012+,则可以使用滞后,如下所示:

Select *, (Profit - PrevProfit)/PrevProfit as [variance %] from (
    Select *, PrevProfit = lag(profit) over(partition by fruit order by [date]) 
    from #fruitdata
) a