Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 以float形式强制转换与int返回不同的结果_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 以float形式强制转换与int返回不同的结果

Sql 以float形式强制转换与int返回不同的结果,sql,sql-server,tsql,Sql,Sql Server,Tsql,从数学上讲,这些结果是相似的,我只是好奇他们的行为。在第一个版本中,当我的局部变量声明为浮点时,舍入函数将停止显示在第二个小数点处的小数。在局部变量声明为int的第二个版本中,舍入函数舍入两位小数,然后添加一组零。为什么变量类型会导致round函数的行为不同 declare @totalpop float set @totalpop = (select count(distinct patid) from members) select @totalpop select edutext ,CO

从数学上讲,这些结果是相似的,我只是好奇他们的行为。在第一个版本中,当我的局部变量声明为浮点时,舍入函数将停止显示在第二个小数点处的小数。在局部变量声明为int的第二个版本中,
舍入
函数舍入两位小数,然后添加一组零。为什么变量类型会导致
round
函数的行为不同

declare @totalpop float 
set @totalpop = (select count(distinct patid) from members)
select @totalpop
select edutext
,COUNT(*) as educationCounts
,round(100.0*COUNT(*)/@totalpop,2)
from
(
select distinct m.patid, e.eduText
    from members as m
    inner join EducationTable as e on e.eduID = m.education
)x
group by x.eduText
--不四舍五入到小数点后两位

declare @totalpop int
set @totalpop = (select count(distinct patid) from members)
select @totalpop
select edutext
,COUNT(*) as educationCounts
,round(100.0*COUNT(*)/@totalpop,2)
from
(
select distinct m.patid, e.eduText
    from members as m
    inner join EducationTable as e on e.eduID = m.education
)x
group by x.eduText

首先,让我们看看圆()函数定义:

Returns a numeric value, rounded to the specified length or precision.
它表示四舍五入到指定的长度,而不是截断到指定的长度

现在,使用int和float生成完全不同的表达式类型。您可以轻松地将它们与以下查询进行比较(我将
COUNT(*)
切换为1,将
@totalpop
切换为1):

这告诉我们,使用int,表达式会给出一个数值。使用一个浮点数,你得到一个浮点数。根据微软的说法,当传递一个浮点时,他们的舍入函数将返回一个浮点,当传递一个数字时,将返回一个十进制

你可以在那里阅读所有关于它的内容:

最后,您可以看到,当零开始时,float get被截断,而数值在达到比例限制之前从未被截断:

select CONVERT(float, 3.330000),          -- 3.33
       CONVERT(numeric(17, 12), 3.330000) -- 3.330000000000

首先,让我们看看圆()函数定义:

Returns a numeric value, rounded to the specified length or precision.
它表示四舍五入到指定的长度,而不是截断到指定的长度

现在,使用int和float生成完全不同的表达式类型。您可以轻松地将它们与以下查询进行比较(我将
COUNT(*)
切换为1,将
@totalpop
切换为1):

这告诉我们,使用int,表达式会给出一个数值。使用一个浮点数,你得到一个浮点数。根据微软的说法,当传递一个浮点时,他们的舍入函数将返回一个浮点,当传递一个数字时,将返回一个十进制

你可以在那里阅读所有关于它的内容:

最后,您可以看到,当零开始时,float get被截断,而数值在达到比例限制之前从未被截断:

select CONVERT(float, 3.330000),          -- 3.33
       CONVERT(numeric(17, 12), 3.330000) -- 3.330000000000

+1到@jamice作为史诗参考,甚至超出主题!;-)+1到@jamice作为史诗参考,甚至超出主题!;-)