如何在 sql 而不是 0 中显示小数

how to show decimals in sql instead of 0

我正在尝试获取百分比,但它显示为零。我想显示两位小数,比如 0.65 这是我选择的查询的一部分:

select count(numbers)/count(othernumbers) decimal(3,2) as"rate"

如果我使用它,它会显示为 0 并去掉其余部分

select count(numbers)/count(othernumbers) as"rate"

还需要将 "count(numbers)" 和 "count(othernumbers)" 都转换为十进制。

select  convert(decimal(5,2), count(numbers))
        /
        convert(decimal(5,2), count(othernumbers))
        as"rate"

这是一个适用于 SSMS(Sql 服务器)的示例:

select Convert(decimal(3,2), convert(decimal(4,2), 1.0) / convert(decimal(4,2), 10.0)) as [rate]

您必须使用此将值转换为十进制,这将为您提供两位小数

SELECT CONVERT( DECIMAL(10,2),
                    ( CONVERT(DECIMAL(10,2), numbers) / 
                      CONVERT(DECIMAL(10,2), othernumbers) ) ) AS rate

你检查过ceil()、floor()和round()了吗

如果你想不舍入任何东西

SELECT TRUNCATE(count(numbers)/count(othernumbers),2) as "rate"

http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_truncate

SELECT FORMAT(this / that, 2) as rate

同时,我质疑COUNT(numbers)是否是你想要的。这计算了在 numbers.

列中有多少行具有非 NULL 值

另外,fraction 通常更像 x / (x+y) -- 意思是 x 占总数 (x+y) 的分数。

A "percentage" 某处需要 100*。 13/20 是 分数 0.65 或 百分比 65.00 .

select convert(decimal(11, 2), 102)

select convert(decimal(11, 2), 102.5)

select convert(decimal(11, 2), 102.74)

select convert(decimal(11, 2), 102.745)

Results: 102.00; 102.50; 102.74; 102.75