SQL Round函数不起作用,有什么想法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1005095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:27:42  来源:igfitidea点击:

SQL Round function not working, any ideas?

sqlsql-serverrounding

提问by Matt

Here is the SELECT statement:

这是 SELECT 语句:

SELECT ROUND(ISNULL(SUM(Price),0),2) As TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

Any ideas of why it's not rounding to two decimal places?

关于为什么不四舍五入到小数点后两位的任何想法?

回答by akf

instead of ROUND(ISNULL(SUM(Price),0),2)you could try CAST(ISNULL(SUM(PRICE),0) AS DECIMAL (4,2))

而不是ROUND(ISNULL(SUM(Price),0),2)你可以尝试CAST(ISNULL(SUM(PRICE),0) AS DECIMAL (4,2))

回答by gbn

What datatype is Price?

什么数据类型是价格?

ROUND in BOL

圆形 BOL

SELECT ROUND(123.4545, 2); -- = 123.4500
GO
SELECT ROUND(123.45, -2);  -- = 100,00
GO

The underlying datatype stays the same: you merely round but leave trailing zeros.

底层数据类型保持不变:您只是舍入但留下尾随零。

For 2 decimal place output, you'd need to CAST to decimal(x, 2)

对于 2 个小数位输出,您需要 CAST 为 decimal(x, 2)

回答by Einstein

You might be having marshalling issues for the column in your environment. Might try an explicit cast CAST(ROUND(...) AS NUMERIC(18,4)) or even just try making 0 0.0. Make sure also you are binding the column with the proper datatype in your application.

您可能在环境中遇到列的编组问题。可能会尝试显式转换 CAST(ROUND(...) AS NUMERIC(18,4)) 甚至只是尝试使 0 0.0。确保您在应用程序中使用正确的数据类型绑定列。

All the cool people use COALESCE instead of ISNULL. COALESCE is portable and you can have as many parameters as you want (not just two!!)

所有很酷的人都使用 COALESCE 而不是 ISNULL。COALESCE 是可移植的,您可以拥有任意数量的参数(不仅仅是两个!!)

Anyway I'm not sure if this was just an example but you may also have DA issues with your data if it had not already been rounded at this stage.

无论如何,我不确定这是否只是一个示例,但如果在此阶段尚未四舍五入,您的数据也可能存在 DA 问题。