SQL打印浮点数较大的小数位

时间:2018-10-17 10:22:05

标签: sql sql-server percentage

我一直在寻找一种解决方案,以获取只需要保留小数点后两位的学生百分比,所以我尝试了

select ROUND(count(fname) * 100.0/(select count(*) from stud_info  WHERE grade = 'FOUR'),2)as 'Total',
status as 'NutritionalStatus'
from stud_info
where grade = 'FOUR'
group by status

然后它最多打印出11个零位的小数位,您能帮我解决什么问题吗? 我有ms sql 2014

1 个答案:

答案 0 :(得分:3)

首先,我建议您这样写:

select status,
       avg(case when grade = 'FOUR' then 1.0 else 0 end) as Total
from stud_info
where grade = 'FOUR'
group by status;

然后,如果要两位小数,请转换为小数:

select status,
       convert(decimal(6, 2),
               avg(case when grade = 'FOUR' then 1.0 else 0 end)
              ) as Total
from stud_info
where grade = 'FOUR'
group by status;

round()会更改,但不会更改类型。应用程序/表示层仍可能决定显示不必要的零。

您还可以使用format()str()将值转换为字符串。