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)
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
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.
Ever need to write reports out to a folder? I have found that creating output files are SA-WEET! (and easy too) The sample script uses BCP to create an HTML file.This process works well for reports that need to be generated nightly and take too long to run in real time. Use an SMTP mail […]