如何使用 T-SQL 针对 iSeries AS/400 数据库将两个整数值的除法转换为小数?
假设以下查询:
SELECT
ID,
COUNT(1) AS NumRecords,
SUM(Quantity) AS TotalQty
SUM(Quantity)/COUNT(1) AS Avg
FROM SOME_TABLE
GROUP BY ID
现在它返回:
ID NumRecords TotalQty Avg
1 15 6 2
我希望它返回 Avg
的 Scale 为 2 的十进制值(即“2.5”)。
我尝试将计算转换为 DECIMAL、NUMERIC、FLOAT 和 VARCHAR,但它始终返回 INTEGER。
Assuming the following query:
SELECT
ID,
COUNT(1) AS NumRecords,
SUM(Quantity) AS TotalQty
SUM(Quantity)/COUNT(1) AS Avg
FROM SOME_TABLE
GROUP BY ID
Right now it returns:
ID NumRecords TotalQty Avg
1 15 6 2
I want it to return a decimal value with a Scale of 2 for Avg
(i.e. "2.5").
I've tried to CAST
the calcluation as a DECIMAL, NUMERIC, FLOAT, and VARCHAR, but it always returns an INTEGER.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将输入转换为计算而不是结果。还有什么原因您不使用
AVG
功能?You need to cast the inputs to the calculation not the result. Also any reason you aren't using the
AVG
function?另一种解决方案是通过隐式强制转换。我发现这也是更简洁的 SQL。精度由乘以 1 时使用的尾随零的数量决定。
An alternative solution is via implicit Casting. I found this to be much cleaner SQL as well. The precision will be determined by the number of trailing zeros used when multiplying by 1.