Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : round and add percent sign

I have the following SQL query that is returning a result of 92.967013425802 and I need it to be formatted like 93% and add the percent sign. I have tried changing the sum to round but I received an error

The function 'round' is not a valid windowing function, and cannot be used with the OVER clause.

My query:

select 
    count(*) * 100.0 / sum(count(*)) over()
from 
    db_table_MetaData
group by 
    MetaValue
order by 
    MetaValue

Any help would be appreciated.

like image 579
DWard Avatar asked Feb 17 '14 05:02

DWard


People also ask

How do you round a percentage in SQL Server?

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.

What does the percent symbol do in SQL?

The SQL LIKE Operator The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

What datatype is used for percentage in SQL?

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage. Show activity on this post. If 2 decimal places is your level of precision, then a "smallint" would handle this in the smallest space (2-bytes). You store the percent multiplied by 100.


2 Answers

select 
    --Cast(Round(count(*) * 100.0 / sum(count(*)), 0) as nvarchar(5) + '%' 
      CAST(Round(count(*) * 100.0 / sum(count(*)), 0) as nvarchar(5)) + '%'
from 
    db_table_MetaData

This should do the trick.

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. However I have no method of checking my syntax right now.

like image 55
Marco Avatar answered Sep 28 '22 15:09

Marco


Strange you got not a valid function. Perhaps you didn't provide the correct parameters?

This worked for me.

select cast(Round('92.967013425802', 0) as nvarchar(10)) + '%'
like image 38
Bob Avatar answered Sep 28 '22 16:09

Bob