sql - Output of cast function
问题描述
I am working on the usage of the Cast
function in SQL Server. If I use explicit value as written in the code. The output is 38 which is the correct value. But I would need to use field names instead of direct values(There is only value of Base, escalator here ; Base =1.15 and escalator=0.05. But when I use field names, the output is 37. The data type of Base and escalator fields is float. I also tried using round function inside cast, did not solve the issue. Could someone out here help me with this. My query below:
Select CAST((3.05-1.15)/0.05 AS INT) -- returns 38
Select ((3.05-1.15)/0.05) --returns 38
Select cast((3.05-base)/Escalator) as int) from table1 -- I am using field names here. Returns 37
解决方案
What is likely happening here is that the base
and Escalator
columns are some kind of non exact floating point type. As a result, the following computation results a value which is slightly less than 38:
(3.05-base) / Escalator = 37.999995 (for example)
Then, when casting to integer, the entire decimal component is being truncated, leaving behind just 37.
One possible workaround to prevent this from happening would be to use NUMERIC
or some other exact type for the base
and Escalator
columns.
推荐阅读
- proxy - 为什么 200 次重写不能在 Netlify 上工作?
- java - Active Directory AD B2C android native msal 无法与 AD 连接
- css - 添加clipPath后svg不可见
- json - 应用带有 Marshmallow 序列化的 JSON Schema
- java - 让应用程序管理的事务在 JPA 和 WebSphere 上工作时遇到问题
- javascript - 由于在 js 移动到下一个 i 之前未调用 promise.then() 导致在循环中读取 excel 文件时出现问题
- python - 在 Python 中使用 Swagger Codegen API 测试程序的错误处理
- reactjs - 如何在构建期间将环境变量注入 React
- sas - 如何根据时间过滤器按两组计算行数?
- elasticsearch - Elasticsearch query_string 通配符不考虑长度