select 语句 t-sql 中的计算值

Computing value in select statement t-sql

我正在尝试在 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 的值在输出中?

因为您的计算使用整数:

4/5 = 0 

逗号后面的所有内容都被删除

是这个:

LEN(Name)/(Abs(LEN('Johny') - LEN(Name)) + LEN(Name)) As Match

4 / ((5 - 4) + 4)

4/ (1 + 4)

4 / 5

= 0

您正在尝试除整数值,其中除数 > 被除数

尝试将一个值转换为浮点数

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