计算SQL Server中的百分比差异

rgx*_*x71 7 sql-server-2008

我有两个月有两个值,例如:

July-2013  1838.08
Aug-2013   3500.08
Run Code Online (Sandbox Code Playgroud)

如何计算8月与7月相比的百分比差异?

RBa*_*ung 30

The formula for this is easy it's (Curr-Prev)*100.0/Prev, what's not clear is how to apply it since we do not know your table definition, contents or keys, and thus do not know how to generically select one month and it's previous value. But, hard-coding it would be like this:

SELECT  
    100.0*(curr.Val - prev.Val) / prev.Val As PercentDiff
FROM yourTable As curr
JOIN yourTable As prev
    ON  curr.MonthStr = 'Aug-2013' AND prev.MonthStr = 'July-2013'
Run Code Online (Sandbox Code Playgroud)

  • 这可以在动态意义上使用吗? (2认同)