我正在尝试运行此查询,但似乎在进行数学计算后没有正确格式化数字。比例应为2,但不会显示。
SELECT 30 / 60 as Diff FROM Table
返回0
SELECT Convert( Numeric(8,2), 30 / 60 ) as Diff FROM Table
返回0.00
如何根据需要返回0.50
?
答案 0 :(得分:3)
您可以尝试以下方法,但实现目标的方法很少。使用变量,或仅对字段本身执行CAST
,CONVERT
。
SELECT (CAST(30 AS DECIMAL(8,2)) / CAST(60 AS DECIMAL(8,2))) as Diff FROM Table
SELECT (CAST(30/60) AS DECIMAL(8,2)) as Diff FROM Table
SELECT (30/60.0) as Diff FROM Table;
SELECT CONVERT(DECIMAL(8,2), 30/60.0) as Diff FROM Table
答案 1 :(得分:1)
在进行除法之前转换为数字或除实数而不是整数。进行整数运算时,会丢弃任何小数。删除分数后转换对你没有任何好处。
SELECT CONVERT(NUMERIC(8,2),30.0/60.0) AS DIFF FROM TABLE
或选择列而不是使用数字
SELECT CONVERT(NUMERIC(8,2),columnA)/CONVERT(NUMERIC(8,2),columnB) AS DIFF FROM TABLE
(转换两者只是为了确保按照我们想要的规则进行划分)