Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate group percentage to 2 decimal places - SQL

I have the following query:

SELECT hostVersion, CONVERT(varchar, 100.0 * count(*) / tot,1)  + '%' as 'Percent'
FROM hostInfo,
(SELECT COUNT(*) as tot FROM hostInfo) x
GROUP BY hostVersion, tot

And receive the following output:

+--------------------------------+
| hostVersion | Percent          |
+--------------------------------+
|    5.0.0    | 26.666666666666% |
+--------------------------------+
|    5.1.0    | 73.333333333333% |
+--------------------------------+

How to I round to only 1 decimal place? (i.e. 26.7% & 73.3%)

like image 304
solar411 Avatar asked Jun 18 '13 16:06

solar411


People also ask

How do I find the percentage between two numbers in SQL?

Finding Percentages between two columns is straightforward. You can simply use the column names and the division operator “/” to divide values in one column by another. The result is a list of values that correspond to the result of the division of all the values in the two columns.

How do I round a percentage in SQL?

In essence you take the 08/15 ROUND() function to get your numeric value. After this you cast it into a nvarchar(x) and add a string to your string.


2 Answers

Try something like this:

CAST(ROUND(100.0 * COUNT(*) / tot, 1) AS DECIMAL(10, 1))
like image 173
Dave Sexton Avatar answered Sep 28 '22 07:09

Dave Sexton


A better choice for conversion is the str() function. (Documented here.)

In addition, you can do your calculation using window functions (assuming that you are using SQL Server 2005 or more recent). Here is my version of the query:

select hi.hostVersion,
       str(((100.0*count(*)) / sum(count(*)) over ()), 5, 2)+'%'
from hostInfo hi
group by hi.hostVersion
like image 25
Gordon Linoff Avatar answered Sep 28 '22 08:09

Gordon Linoff