HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

SQL percentage calculation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sqlcalculationpercentage

Problem

I have created a query in which there is a column that calculates a percentage:

SELECT 
     u.User_FirstName
    ,l.[Total Leads]
    ,SUM(s.SalesCount) AS [New Clients]
    ,c.Target
    ,CONVERT(VARCHAR, CONVERT(DECIMAL(11,0),ROUND((CONVERT(DECIMAL(11,2), SUM(s.SalesCount)) / l.[Total Leads]) * 100, 0))) + '%'


As you can see, that last column is my percentage column, which uses a lot of CONVERT. I was wondering if there is a simpler or faster way to get a two-digit percentage in SQL Server 2008.

Solution

I feel that rofl pretty well covered how this could be done differently, but I want to point out what I feel to be an issue.

You really shouldn't be formatting the decimal results as a string. Formatting should be done in whatever application consumes the data you're sending it. As a user, I would be pretty upset to receive a "percentage" that I couldn't do any mathematical analysis on without first splitting out the "%" character, dividing by 100, and then formatting it as a percentage natively.

Select CONVERT(decimal(5,0), 1.0 * SUM([SalesCount]) / [Total Leads])

Code Snippets

Select CONVERT(decimal(5,0), 1.0 * SUM([SalesCount]) / [Total Leads])

Context

StackExchange Code Review Q#58369, answer score: 8

Revisions (0)

No revisions yet.