【问题标题】:Replace Function is rounding Up value in SQL替换函数在 SQL 中向上舍入值
【发布时间】:2023-02-09 01:13:05
【问题描述】:

我有一个查询

select distinct
r.max_range,    
convert(float,isnull(replace(r.max_range,0.0,100000000.0),100000000.0)) as max_amt,
convert(float,r.max_range) as 'convert_float',
replace(r.max_range,0.0,100000000.0) as 'replace_question'
from    #temp t1
join    LTR_Amounts r on (isnull(t1.amt,0) >= r.min_range 
and     isnull(t1.amt,0) <= convert(float,isnull(replace(r.max_range,0.0,100000000.0),100000000.0)))
where   r.category_id = 3
and     r.inactive <> 'y'

产生以下内容 - 我有 100,000 的金额,它应该属于

max_range max_amt convert_float replace_question
24999.99 25000 24999.99 25000
49999.99 50000 49999.99 50000
99999.99 100000 99999.99 100000
199999.99 200000 199999.99 200000

这可以按如下方式运行

declare @max_range float = 99999.99
select distinct
@max_range,                                 convert(money,isnull(replace(@max_range,0.0,100000000.0),100000000.0)) as max_amt,
convert(money,@max_range) as 'convert_float',
replace(@max_range,0.0,100000000.0) as 'replace_question'
max_range max_amt convert_float replace_question
99999.99 100000.00 99999.99 100000

手头的问题是,如果您在我使用替换作为查询的一部分时就可以看到所有地方,那么它会将值四舍五入。如果我在使用替换作为公式的一部分时得到 99999.99 的 max_range,它会将其视为 1000000,但我需要它继续将其视为 99999.99

现有的业务规则要求我使用替换(或它的某个版本),因为有时值是 0.0,然后我需要用某个最大值替换它。

如何将我的公式保留为我加入的一部分(使用替换)

【问题讨论】:

  • REPLACE 是为了字符串/文本,而不是数字 - 您的查询正在执行从数字到文本的隐式转换,然后再返回,这是无意义的操作。
  • 我个人建议真正的问题是您正在使用 float 并将其视为字符串。
  • “现有的业务规则要求我使用 replace(或它的某个版本),因为有时值是 0.0,然后我需要用某个最大值替换它。”- 使用CASENULLIF - 而不是REPLACE
  • ...另外,您描述的“业务规则”是表示层问题,因此不应该在 SQL 中实现,代替人类可读显示的值应该由您的应用程序或系统中实际在屏幕上呈现数据的部分(即您的报告引擎)完成。
  • convert(float,isnull(replace(r.max_range,0.0,100000000.0),100000000.0))) <-- 请告诉我这不是感觉不错写给你的时候...

标签: sql sql-server replace decimal rounding


【解决方案1】:

首先,浮点数是近似值,即并非数据类型范围内的所有值都可以准确表示 - 有关详细信息,请参阅here

其次,REPLACE 将字符或二进制数据类型作为参数,因此您的查询会隐式地从近似值转换为字符串。

我建议使用适当的固定数字数据类型,如 decimal,并将 REPLACE 更改为 CASE 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多