首先,我在Microsoft Visual Studio IDE中进行开发。所以,我想要获得的是查询的结果,该列是 nvarchar数据类型。此查询的目标是在某个时刻向用户提供数据库中有多少不同扩展的百分比。 为了更好地解释你们,我会在这里发布:
SELECT Filetype AS 'Extensão',
COUNT(*) AS 'Nº de ficheiros',
((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile)) AS 'Percentagem (%)',
SUM(Filesize) AS 'Total(KB)'
FROM infofile
GROUP BY Filetype
UNION ALL
SELECT '---------------',
COUNT('Nº de extensões'),
((COUNT(Filetype) * 100) / (SELECT COUNT(Filetype) FROM infofile)),
SUM(Filesize)
FROM infofile
所以,我试图用我的查询((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile)) AS 'Percentagem (%)'
这一行得到的结果只是2个小数位和这一列的每一行。我有一行((COUNT(Filetype) * 100) / (SELECT COUNT(Filetype) FROM infofile))
,它给出了应该是100的总百分比,但这显示我100.00000。
这是我现在得到的输出。
答案 0 :(得分:0)
执行CAST
将NVARCHAR
转换为DECIMAL
:
SELECT Filetype AS 'Extensão',
COUNT(*) AS 'Nº de ficheiros',
CASE WHEN (COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile) = 100.0
THEN '100'
ELSE CONVERT(VARCHAR, CAST(((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile))) AS DECIMAL(10,2))
END AS 'Percentagem (%)',
SUM(Filesize) AS 'Total(KB)'
FROM infofile
...
答案 1 :(得分:0)
您可以使用格式化功能
Format((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile),'0.##') AS 'Percentagem (%)',