2017-08-24 83 views
2

我有下面这个表:在列中有两个天计算方差

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 %] 

但又不能完全肯定这是要做到这一点

回答

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

+1

你是先生,是一个传奇。谢谢,这个作品完美! – VS1SQL

1

你是最有效的方法不计算“方差” - 在统计中有一个特定的定义 - 但是“差异”。对于这一点,使用lag()

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

我会做差异是 “近期” - “以前”。你似乎正在走另一条路,所以只是颠倒了操作数的顺序。

+0

嗨,搞不清这个回答我的问题。为了澄清我试图实现上述返回的例子为利润不移动平均,。下面的答案是更多我正在寻找。然而需要一个更动态的方式来编写日期来计算差异。 – VS1SQL

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 
+0

嗨,这是我最初的,但是,有没有办法写它,使利润和预收益不必手动输入?...因为这当前的解决方案意味着我需要键入每个日期E.G. '[2014-01-17] - [2014-01-16])/ [2014-01-16]''[2014-01-18] - [2014-01-17])/ [2014-01-17 ''为多行。 – VS1SQL

+0

您的意思是“利润和预收益不必输入”?你能提供你的样本数据吗? –

+0

基本上我试图实现上述**第二表**中的**方差**列。我已经用excel来显示期望的差异列答案(例如利润** 3.12 ** - ** 5.61 **)/(预先利润** 5.61 **)= ** - 0.443850267 **)并将其放置在我想要返回的示例数据中。你的脚本引入了一个名为'preprofit'的新列,它不在我的数据表中 – VS1SQL