0

我正在尝试运行此查询,但在进行数学计算后似乎没有正确格式化数字。比例应为 2,但不会按应有的方式显示。

SELECT 30 / 60 as Diff FROM Table

这返回为0

SELECT Convert( Numeric(8,2), 30 / 60 ) as Diff FROM Table

这返回为0.00

我如何让它0.50根据需要返回?

4

2 回答 2

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

请查看此MSDN 文章以供进一步参考

于 2012-12-01T04:26:13.017 回答
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

(转换两者只是为了确保根据我们想要的规则完成划分)

于 2012-12-01T04:24:51.883 回答