计算表格中行之间的百分比差异

时间:2015-05-14 14:01:33

标签: sql sql-server

我有一张表格,我想计算一组帐号,福利和年份的行间百分比差异。我正在使用SQL 2008

BEFORE示例

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

示例AFTER(我希望看到的)

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

2 个答案:

答案 0 :(得分: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

如果缺少一个月,这将再次返回零。

答案 1 :(得分: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