试图计算月比百分比增加/减少

时间:2014-03-28 13:53:03

标签: sql sql-server excel sum calculated-field

我正在尝试计算数据行的月份百分比变化。例如,我当前的输出是:

DataDate |LocationId|Payment|MoM [Current placeholder column in script]             
12-1-2013|LocationA |$5.00  |      
1-1-2014 |LocationA |$10.00 |    
2-1-2014 |LocationA |$100.00|   
12-1-2013|LocationB |$50.00 |    
1-1-2014 |LocationB |$25.00 |    
2-1-2014 |LocationB |$50.00 |

我将结果粘贴到Excel中,然后使用以下公式计算MoM:
    ((CurrentDataDate Payment / PreviousDataDate Payment)-1)]

我无法弄清楚在哪里开始尝试实现这一点所以我无法提供任何编码,我已经尝试了...我已经读过并尝试过用于计算运行总数的相关标量查询并试图改变它要做到这一点......没有骰子......我尝试过加入和子查询,但我会承认我的子查询能力不够充分。

用于调用此信息的代码是:

Declare @BeginDate as DateTime
Declare @EndDate as DateTime    
Set @BeginDate = '12-01-2013'
Set @EndDate = '02-01-2014'

Select DataDate,LocationId,Payment,0 as MoM
From dbo.mytableview
Where DataMonth between @BeginDate and @EndDate

所需的输出是:

DataDate |LocationId|Payment|MoM              
12-1-2013|LocationA |$5.00  |      
1-1-2014 |LocationA |$10.00 |1.0  [or 100%]  
2-1-2014 |LocationA |$100.00|9.0  [or 900%] 
12-1-2013|LocationB |$50.00 |    
1-1-2014 |LocationB |$25.00 |-.50 [or -50%]  
2-1-2014 |LocationB |$50.00 |1.0  [or 100%]

我正在使用Microsoft SQLServer 2008 R2。如果需要,我也可以使用2012版本。

3 个答案:

答案 0 :(得分:1)

这适用于SQL Server 2012:

with x as (
select datadate, locationid, payment,
    lag(payment) over(partition by locationid order by datadate) as prev_payment
from table
)
select *, (payment/prev_payment)-1
from x

答案 1 :(得分:0)

虽然院长的解决方案更好,但我还是想为完全没有SQL Server 2012的人发布一个解决方案(因为我已经在院长发布他之前已经开始了)。

这可以使用公用表表达式和Row_Number()函数来完成:

WITH CTE AS 
(
SELECT Row_Number() OVER (PARTITION BY locationid ORDER BY datadate) AS RN, datadate, locationid, payment
FROM table
)

SELECT 
    CTE2.*, 
    (CTE2.payment / CTE1.payment) - 1 AS MOM
FROM
    CTE AS CTE1 RIGHT OUTER JOIN
    CTE AS CTE2
ON
    CTE1.RN = CTE2.RN-1
AND
    CTE2.locationid = CTE1.locationid 
ORDER BY
    locationid 

答案 2 :(得分:0)

这是另一个解决方案,适用于早期版本:

select *, (t2.payment/t1.payment)-1
from #t t1
left join #t t2 on datediff(month, t1.datadate, t2.datadate)=1
and t1.locationid = t2.locationid

但是,这种自联接解决方案通常不能很好地处理大型数据集,在这种情况下首选游标解决方案。