1

为什么CALC下面的 TSQL 查询中没有计算出值?

SELECT
    D1, D2, (D1+D2) As 'Sum', ((D1/(D1+D2))*100) As CALC
FROM
    (SELECT 3 As D1, 6 As D2) A

这是我得到的结果:

D1          D2          Sum         CALC
----------- ----------- ----------- -----------
3           6           9           0
4

2 回答 2

2

整数除以整数生成整数,因此如果操作数都是整数,则除法运算将截断结果的小数部分。将一个更改为浮点数或小数以修复它。

跑去 Select 5 / 6, 5 / 6.0看看我的意思

使用演员表修复您的代码...

 SELECT  D1, D2, (D1+D2) As 'Sum', 
    ((D1/ Cast(D1+D2 as Float))*100) As CALC
 FROM (SELECT 3 As D1, 6 As D2) A

或者只是使值浮动以开始:

 SELECT  D1, D2, (D1+D2) As 'Sum', 
    ((D1/ (D1+D2))*100) As CALC
 FROM (SELECT 3.0 As D1, 6.0 As D2) A
于 2013-05-09T17:37:46.307 回答
1

整数除法四舍五入到零
移动 100。你仍然会得到一些四舍五入。
如果您不能容忍任何舍入,则不要使用整数。

SELECT
    D1, D2, (D1+D2) As 'Sum', D1/(D1+D2) as frac, (D1*100)/(D1+D2) As pct
FROM
    (SELECT 3 As D1, 6 As D2) A
于 2013-05-09T17:42:54.053 回答