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%)
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.
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.
Try something like this:
CAST(ROUND(100.0 * COUNT(*) / tot, 1) AS DECIMAL(10, 1))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With