SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Calculating Percentage Change

By Ryan, 2007/03/02

Total article views: 653 | Views in the last 30 days: 88

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.

SELECT
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.

Cheers!

By Ryan, 2007/03/02

Total article views: 653 | Views in the last 30 days: 88
Your response
 
 
Related tags
 
Like this? Try these...
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com