我正在尝试在select语句中计算一个值,但令人惊讶的是它会导致0。
SELECT Top(1) Name,
LEN(Name) AS Equals,
Abs(LEN('Johny') - LEN(Name)) AS NotEquals,
LEN(Name)/(Abs(LEN('Johny') - LEN(Name)) + LEN(Name)) As Match
FROM Demo
WHERE Name = LEFT( 'Johny' , LEN(Name) )
ORDER BY LEN(Name) DESC
输出:
Name Equals NotEquals Match
John 4 1 0
为什么输出中match
字段0
的确切值是什么?
答案 0 :(得分:2)
因为你的计算使用整数:
4/5 = 0
删除逗号后面的所有内容
答案 1 :(得分:2)
这是:
LEN(Name)/(Abs(LEN('Johny') - LEN(Name)) + LEN(Name)) As Match
4 / ((5 - 4) + 4)
4/ (1 + 4)
4 / 5
= 0
答案 2 :(得分:2)
你试图划分整数值,其中除数>分红
尝试将一个值转换为float
SELECT Top(1) Name,
LEN(Name) AS Equals,
Abs(LEN('Johny') - LEN(Name)) AS NotEquals,
cast(LEN(Name) as float)/(Abs(LEN('Johny') - LEN(Name)) + LEN(Name)) As Match
FROM Demo
WHERE Name = LEFT( 'Johny' , LEN(Name) )
ORDER BY LEN(Name) DESC