如何使SQL查询结果以2个小数显示

时间:2018-08-17 12:29:57

标签: sql sql-server

我偶然遇到了一个问题,使该代码仅显示两位小数

SELECT 
SUM(CAST(
Size * 8 as Decimal)/1024
) as [Size in MB]

FROM 
sysfiles

目前,它以7位小数返回我的数据库大小:/

3 个答案:

答案 0 :(得分:0)

我建议转换为带有两个位置的十进制格式:

select convert(decimal(20, 2), size * 8.0/1024) as [Size in MB]
from sysfiles;

这会将值转换为正确的 type 。但是,如果要确保将值显示为正确的精度/小数位数,则可以使用format()str()

select str(size * 8.0/1024, 20, 2) as [Size in MB]
from sysfiles;

答案 1 :(得分:0)

您可以仅使用cast(xxx as decimal({length},{precision}))

来转换小数
SELECT 
SUM(CAST(
Size * 8 as Decimal(20,2))/1024
) as [Size in MB]

FROM 
sysfiles

答案 2 :(得分:0)

只需将总和本身转换为小数

SELECT CAST(SUM(CAST(Size * 8 AS DECIMAL(18,2)) /  1024) AS DECIMAL(18,2)) [Size in MB]