6

我有以下查询:

SELECT hostVersion, CONVERT(varchar, 100.0 * count(*) / tot,1)  + '%' as 'Percent'
FROM hostInfo,
(SELECT COUNT(*) as tot FROM hostInfo) x
GROUP BY hostVersion, tot

并收到以下输出:

+--------------------------------+
| hostVersion | Percent          |
+--------------------------------+
|    5.0.0    | 26.666666666666% |
+--------------------------------+
|    5.1.0    | 73.333333333333% |
+--------------------------------+

如何四舍五入到小数点后一位?(即 26.7% 和 73.3%)

4

3 回答 3

5

尝试这样的事情:

CAST(ROUND(100.0 * COUNT(*) / tot, 1) AS DECIMAL(10, 1))
于 2013-06-18T16:10:11.847 回答
4

转换的更好选择是str()函数。(记录在这里。)

此外,您可以使用窗口函数进行计算(假设您使用的是 SQL Server 2005 或更新版本)。这是我的查询版本:

select hi.hostVersion,
       str(((100.0*count(*)) / sum(count(*)) over ()), 5, 2)+'%'
from hostInfo hi
group by hi.hostVersion
于 2013-06-18T16:09:44.880 回答
0
SELECT hostVersion, CONVERT(varchar, ROUND(100.0 * count(*) / tot,2),1)  + '%' as 'Percent'
FROM hostInfo,
(SELECT COUNT(*) as tot FROM hostInfo) x
GROUP BY hostVersion, tot
于 2013-06-18T16:05:29.910 回答