为什么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
答案 0 :(得分: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
答案 1 :(得分: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