计算列中两天之间的差异

Calculating Variance between two days in a column

我下面有这个table:

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 为增量按日期计算方差,因此例如返回的 table 会像:

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

我不知道该怎么做。

我想如果日期是 headers 而不是行,那么计算方差百分比会更容易

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

但同样不能完全确定这是最有效的方法

您计算的不是 "variance"——它在统计中有特定的定义——而是 "difference"。为此,使用 lag():

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

我会做 "recent" - "previous" 的区别。你好像走反了,所以把操作数的顺序颠倒一下就可以了。

如果您使用的是 SQL Server 2012+,您可以按如下方式使用延迟:

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

您可以尝试使用 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