SQL divide two integers and get a decimal value error(SQL将两个整数相除得到十进制值错误)
问题描述
在 SQL 语句中,我试图将两个整数相除(在下面的代码中,整数 1 是abc",在我的代码中整数 2 是xyz"),然后得到一个小数的结果(我的代码中的 def以下).小数结果应该只有前导 1 或 0,后跟一个小数和小数点后的 3 个数字.但是我的代码一直返回一个没有小数的直 0.
In an SQL statement, I am trying to divide two integers (integer 1 is "abc" in my code below, integer 2 is "xyz" in my code), and get a result as a decimal (def in my code below). The decimal result should have a leading 1 or 0 only, followed by a decimal and 3 numbers after the decimal. However my code keeps returning a straight 0 with no decimals.
SELECT CONVERT(DECIMAL(4,3), abc/xyz) AS def
此代码结果为0",而我想要的是0.001"或0.963"之类的东西.我相信它仍然将def"视为整数,而不是小数.
This code results in "0", when what I want is something like "0.001" or "0.963". I believe that it is still looking at "def" as an integer, and not as a decimal.
我也尝试在 abc 和 xyz 上使用 CAST,但它返回相同的东西.我也试过以下代码:
I have also tried using CAST on abc and xyz but it returns the same thing. I have also tried the following code:
SELECT CONVERT(DECIMAL(4,3), abc/xyz) AS CONVERT(DECIMAL(4,3)def)
但这给了我一个错误,说CONVERT"一词附近有语法错误.
But this gives me an error, saying there is a syntax error near the word "CONVERT".
推荐答案
在除法之前转换为十进制,而不是之后.答案格式的转换.
Convert to decimal before the divide, not after. The convert for answer format.
SELECT
CONVERT( DECIMAL(4,3)
, ( CONVERT(DECIMAL(10,3), abc) / CONVERT(DECIMAL(10,3), xyz) )
) AS def
这篇关于SQL将两个整数相除得到十进制值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL将两个整数相除得到十进制值错误


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01