2015-05-14 96 views
2

我有一張表,我想計算一組帳號,收益和年份的行之間的百分比差異。我使用SQL 2008計算表上各行之間的百分比差異

例子之前

AccountNbr Benefit Year Month Value Diff 
------------ ------- ---- ----- ----- ---- 
123   A   2014 11 10 
123   A   2014 12 20 
123   A   2015 1  10 
123   A   2015 2  20 
123   A   2015 3  40 
123   B   2015 1  50 
123   B   2015 2  100 
123   B   2015 3  150 

實例後(我想看看)

AccountNbr Benefit Year Month Value Diff 
------------ ------- ---- ----- ----- ---- 
123   A   2014 11 10  0 
123   A   2014 12 20  100 
123   A   2015 1  10  -50 
123   A   2015 2  20  100 
123   A   2015 3  40  100 
123   B   2015 1  50  0 
123   B   2015 2  90  80 
123   B   2015 3  40  -55 
+0

什麼是SQL服務器上的版本? – dnoeth

+0

添加一個2014年12行的例子,只是爲了讓它更安全一點。 – jarlh

+0

與「跑步總計」相同,只是執行百分比差異而非總和。 –

回答

1

您可以使用ROW_NUMBER()來識別每個AccountNbr, Benefit分區中的前一行。然後,您可以LEFT JOIN與前行和計算的百分比差異(如果那是你真正想要的畢竟!):

;WITH CTE AS (
    SELECT AccountNbr, Benefit, Year, Month, Value, 
      ROW_NUMBER() OVER (PARTITION BY AccountNbr, Benefit 
          ORDER BY Year, Month) AS rn 
    FROM mytable 
) 
SELECT c1.AccountNbr, c1.Benefit, c1.Year, c1.Month, c1.Value,    
     CAST(COALESCE (((c1.Value - c2.Value) * 1.0/c2.Value) * 100, 0) AS INT) AS Diff 
FROM CTE AS c1 
LEFT JOIN CTE AS c2 
ON c1.AccountNbr = c2.AccountNbr AND c1.Benefit = c2.Benefit AND c1.rn = c2.rn + 1 

SQL Fiddle Demo

+0

工作得很好,謝謝! – thirty

1

假設你有一排每年/月,你可以做一個自我加入:

select t1.* 
    ,coalesce(100*(t1.value - t2.value)/t2.value, 0) 
from tab as t1 
left join tab as t2 
    on t1.AccountNbr = t2.AccountNbr 
and t1.Benefit = t2.Benefit 
and t1.year = case when t2.month < 12 then t2.year else t2.year +1 end 
and t1.month = case when t2.month < 12 then t2.month +1 else 1 end 

如果一個月缺失,這將返回零。