Search code examples
sqlsql-servercastingdecimalnvarchar

How to correct this T-SQL syntax to get an output with no decimal places?


I am using SQL Server 2016 and I have the following T-SQL code in my query:

CAST(ROUND([Count of Bookings] * 100.0 / SUM([Count of Bookings]) OVER (PARTITION BY [Market Final], [PropertyCode]), 0) AS NVARCHAR(15)) + '%'

An example of the current output of this code is: 40.000000000000%

I was expecting the output to be: 40%

As a note (I don't know if this is relevant): if I change the number in the nvarchar(x) to lower than 15, I get the following error:

Arithmetic overflow error converting expression to data type nvarchar.


Solution

  • Use str() instead of cast():

    str(round([Count of Bookings] * 100.0 /
              sum([Count of Bookings]) over(PARTITION BY [Market Final], [PropertyCode]
             ) , 0), 3, 0)  + '%'
    

    Actually, I think str() rounds by default (could the documentation be any less clear on this subject?):

    str([Count of Bookings] * 100.0 /
        sum([Count of Bookings]) over (PARTITION BY [Market Final], [PropertyCode]
                                      ), 3, 0)  + '%'