假设我有以下代表税收的数据:
SELECT trunc(i*i, 3) tax
FROM generate_series(1.17, 5) i;
tax
--------
1.368
4.708
10.048
17.388
(4 rows)
PostgreSQL中是否有任何不错的方法将mill余数放入下一行,如果当前行是最后一行,则必须保留所有剩余项。
所以,我需要做到以下几点:
tax
--------
1.360
4.710
10.050
17.392
(4 rows)
它可以是查询或SQL / PL / pgSQL函数。
答案 0 :(得分:3)
下一行和最后一行仅在定义了排序顺序后才有意义。我假设排序顺序是由tax asc
定义的。
第一个子查询将行号添加到数据中,而第二个子查询计算行数。下一部分是基于行数增加的递归:
with recursive data as (
select trunc(i*i, 3) tax, row_number() over (order by i) as rn
from generate_series(1.17, 5) i
),
count as (
select count(*)
from data
),
result as (
select
tax, rn,
floor(tax* 100)/100 as new_tax,
tax- floor(tax* 100)/100 as remainder
from data
where rn = 1
union all
select
d.tax, d.rn,
case d.rn
when count then d.tax+ r.remainder
else floor((d.tax+ r.remainder)* 100)/100 end as new_tax,
d.tax+ r.remainder- floor((d.tax+ r.remainder)* 100)/100 as remainder
from data d
join result r on d.rn = r.rn+ 1
cross join count
)
select new_tax as tax
from result
order by rn;