SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Calculating Percentage Change

By Ryan,

To provide data analysis you may need to perform some basic trend analysis. For example, if you want to identify the percentage of change in the number of orders received from one month to the next. The challenge to providing that on the fly is the change can be either an increase or a decrease, you can risk divide by zero errors, or your users may need a general percentage regardless of direction.

I wrote this function (SQL 2000) to handle the various scenarios I was seeing, and used it in a couple select statements that ran aggregations to return sum values. To give an example using Northwind, this query will return the total orders per month:

SELECT Count(*), Month(OrderDate)
FROM Northwind..Orders
GROUP BY Month(orderDate)
ORDER BY Month(orderDate)

January has 88 orders and February 83, a decrease in sales by -5.68%. Other way around it would have been an increase by 6.02%. If you didn't care about the direction and only wanted the absolute change it would be an average of 5.85%. This function will let you retrieve any of those values.

dbo.PercentageChange (a.prev, b.curr, 0, 0), -- -5.86%
dbo.PercentageChange (b.curr, a.prev, 0, 0), -- 6.02%
dbo.PercentageChange (a.prev, b.curr, 1, 0) -- 5.85%
FROM (SELECT Count(*) as [prev] FROM Northwind..Orders WHERE Month(OrderDate) = 1) as [a],
(SELECT Count(*) as [curr] FROM Northwind..Orders WHERE Month(OrderDate) = 2) as [b]

Any suggestions for improvement are welcome. You can certainly embed the math directly in a sql query and execute faster, the value here is mainly encapsulating the logic and reuse. I hope you find it handy.


Total article views: 2266 | Views in the last 30 days: 7
Related Articles

can't query on 'Order Details' table in Northwind

Northwind - Order Details


OrderDate = Today

How to make code below working? (OrderDate is date type) I want to add some code if OrderDate is ...


Select all months bewtween two dates

Select all months bewtween two dates


Month Names display order incorrect in reports (using Cube data)

Month Names display order incorrect in reports (using Cube data)


Selecting a Value of the Order Within a Group

Select To Indicate Order Number Within a Group

sqlinsider scripts