我在数字之间分割 0.00xxx 浮点值时遇到问题。 以下是输入 data 的示例 0 是 1-3 个 float 的和。 结果我希望看到四舍五入的数字而不丢失 1-3 的总和:
输入:
0 313.726
1 216.412
2 48.659
3 48.655
输出:
0 313.73
1 216.41
2 48.66
3 48.66
它应该如何工作: 想法是将最低的其余部分(在我们的示例中,它是值 216.412 的 0.002)拆分为最高的部分。 0.001 到 48.659 = 48.66 和 0.001 到 48.655 = 48.656 之后我们可以对数字进行舍入而不会丢失数据。
昨天解决这个问题后,我找到了解决方案。我认为查询应该是这样的。
select test.*,
sum(value - trunc(value, 2)) over (partition by case when id = 0 then 0 else 1 end) part,
row_number() over(partition by case when id = 0 then 0 else 1 end order by value - trunc(value, 2) desc) rn,
case when row_number() over(partition by case when id = 0 then 0 else 1 end order by value - trunc(value, 2) desc) / 100 <=
round(sum(value - trunc(value, 2)) over (partition by case when id = 0 then 0 else 1 end), 2) then trunc(value, 2) + 0.01 else trunc(value, 2) end result
from test;
但对我来说,在获取结果时添加 const 值“0.01”仍然很奇怪。
有任何改进此查询的想法吗?
最佳答案
在显示结果时,您可以使用 round() sql 函数。 Round() 的第二个参数是要将数字四舍五入到的有效位数。在测试表上发出此选择:
select id, round(value, 2) from test;
给你以下结果
0 313.73
1 216.41
2 48.66
3 48.65
一般情况下,可以使用存储的数字进行求和,然后使用 round() 函数来呈现结果:这里有一种方法,可以对完整的有效数字进行求和,然后使用 round() 函数来呈现结果最终结果:
select sum(value) from test where id != 0
给出结果:313.726
select round(sum(value), 2) from test where id != 0
给出结果:313.73
顺便说一下,我有两个观察结果:
1) 您对 id = 3 给出的舍入让我感到困惑:48.654 四舍五入为 48.65,而不是 48.66,保留两位有效数字。我错过了什么吗?
2) 严格来说,这个问题不是标签上的 pl/sql 问题。这完全属于sql的范畴。然而,pl/sql 中也有一个 round() 函数,并且适用相同的原理。
关于sql - 在数字列表之间拆分 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810677/