SQL:即使在尝试强制转换后,除非返回准确的结果

时间:2017-06-26 23:26:08

标签: sql division

提前感谢您的帮助。基本上我没有得到小数结果: 这是我的代码:

select 
practitioner_id, 
count([Number of Acorns Used]) as [Surveys Used], 
count(patid) as [Number of Clients], 
cast(count(cast ([Number of Acorns Used] as float))/
count(cast (patid as float)) as decimal(10,2)) as [Survey Use Rate]
from #Results
group by practitioner_id
order by count([Number of Acorns Used]) desc

以下是一些部分结果(从业者被删除):

removed 6   46  0.00
removed 5   11  0.00
removed 5   20  0.00
removed 4   26  0.00
removed 4   28  0.00
removed 4   6   0.00
removed 4   32  0.00
removed 2   2   1.00
removed 1   1   1.00

![数据结果] [1]:https://i.stack.imgur.com/IZrgI.png

4 个答案:

答案 0 :(得分:2)

你没有得到小数结果的原因是count()的输出是一个int,所以你想把演员表移到count()函数之外。

select 
practitioner_id, 
count([Number of Acorns Used]) as [Surveys Used], 
count(patid) as [Number of Clients], 
 cast(count([Number of Acorns Used]) as decimal(10,2))/
 cast(count(patid) as decimal(10,2))
  as [Survey Use Rate]
from #Results
group by practitioner_id
order by count([Number of Acorns Used]) desc

答案 1 :(得分:0)

Float不是精确的数值数据类型。所以它有时会给你略微偏离的结果。请改用decimal(7,2)。或者你需要适合你的数字。 https://docs.microsoft.com/en-us/sql/t-sql/data-types/numeric-types

答案 2 :(得分:0)

你的演员阵容在错误的地方。例如,结果是整数:

count(cast ([Number of Acorns Used] as float))

将其更改为cast(count([Number of Acorns Used]) as DECIMAL(19,6)

您可以通过单独选择列来确定这一点。

我还建议使用decimal not float(这是不精确的,实际使用非常有限)

所以试试这个完整的表达方式:

cast(count([Number of Acorns Used]) as DECIMAL(19,6))
/
cast(count(patid) as decimal(10,2)) as [Survey Use Rate]

事情是......除非你使用DISTINCT,否则我不会期望这些计数会返回不同的数字。但我不知道这是什么类型的SQL。

答案 3 :(得分:0)

根本问题是您的数据库(可能是SQL Server)进行整数除法。因此,当您分割两个整数时,结果是一个整数。然后你可以将它投射到你喜欢的任何地方,但过程是:3/2 - > 1 - > 1.00。

我通常只需将1.0的值乘以1.0来进行除法:

select practitioner_id, 
       count([Number of Acorns Used]) as [Surveys Used], 
       count(patid) as [Number of Clients], 
       (count([Number of Acorns Used]) * 1.0 /
        count(patid)
       ) as [Survey Use Rate]
from #Results r
group by practitioner_id
order by [Surveys Used] desc;

正如其他人所说,计算浮点数与计算整数,计算字符串或计算日期相同。 count()始终返回一个整数。