• subscribe
November 26, 2002 12:00 AM

Calculating Percentage

SQL Server Pro
InstantDoc ID #27112
Downloads
27112.zip

Administrators often have to calculate percentages of data that meet a condition. To make such calculations easier, I developed a solution that uses T-SQL. Here are a couple of examples that use the Northwind database to show how this code works.

Suppose you want to prepare a report that shows a percentage of sales to each customer for three product categories: beverages, confections, and others. You can use the code that Listing 2 shows to perform this calculation. The code groups all the data in Northwind by CompanyName and calculates a percentage by using a CASE statement inside a SUM() function.

The code in Listing 2 is simple. But let's look at a more complex example. Say you need a report that shows, for each customer, a percentage of sales of all the products in the three categories defined above. To accomplish this task, I rely on the fact that COUNT(*), COUNT(1), and SUM(1) are equal. By using a CASE statement inside a SUM() function, as Listing 3 shows, you can find the number of records that fall into one of the three specified categories. To calculate a percentage, you need to convert that number to a float value and divide by the total sales of all the products.



ARTICLE TOOLS

Comments
    There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here
  • SP1?
    I know there is a SP1 for SQL 2008 R2 available....and there is a "feature pack" as well... ...
  • SQL database mirroring
    I have SQL Server 2008 R2 Enterprise 64bit on Windows 2008 R2 Enterprise 64bit.  Each SQL Server has...
  • Dell Compellent Disk Drive
    Does anybody has experience with Dell Compellent Disk Drive? Basically, this system manages all disk...
  • Sql server performance tuning
    I need to find a tool that help me to optimize sql server,queries,improve the performance and solve ...