如何将0加到int

时间:2018-07-26 23:39:42

标签: sql sql-server tsql number-formatting

我有以下SQL查询

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

我得到的结果为250,但我想将结果显示为250.0000。我已经看过SQL的RIGHTLEFT函数,但还不能弄清楚。 averageSales的数据类型为int。

我也尝试了以下方法

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;

但这会导致

  

将int转换为数值数据类型的算术溢出错误。

2 个答案:

答案 0 :(得分:6)

使用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;

答案 1 :(得分:0)

CASTDECIMAL一起使用NVARCHAR

GROUP BY CAST(SalesPerson as DECIMAL(8,4))