Search code examples
sqlsql-servert-sqlnumber-formatting

How to add 0's to an int


I have the following SQL query

SELECT MAX(averageSales)
FROM (
    SELECT AVG(TotalSale) AS averageSales
    FROM [Practice].[dbo].[Sales]
    GROUP BY CAST(SalesPerson AS NVARCHAR(100))
) AS Query1;

I get the result as 250 but I want to display the result as 250.0000. I have looked at RIGHT and LEFT function for SQL but have not been able to figure it out yet. The data type for averageSales is an int.

I tried the following approach as well

SELECT 
    MAX(averageSales), 
    CAST(MAX(averageSales) AS decimal(4,4))
FROM (
    SELECT AVG(TotalSale) AS averageSales 
    FROM [Practice].[dbo].[Sales]
    GROUP BY CAST(SalesPerson AS NVARCHAR(100))
) AS Query1;

but this results in

Arithmetic overflow error converting int to data type numeric.


Solution

  • Use FORMAT(..., '#.0000'):

    SELECT FORMAT(MAX(averageSales), '#.0000') FROM 
    (
        SELECT AVG(TotalSale) AS averageSales FROM [Practice].[dbo].[Sales]
        GROUP BY CAST(SalesPerson AS NVARCHAR(100))
    ) AS Query1;