代码之家  ›  专栏  ›  技术社区  ›  ole Gabriel

将除法的余数放入下一行

  •  3
  • ole Gabriel  · 技术社区  · 7 年前

    假设我有以下代表税收的数据:

    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函数。

    1 回复  |  直到 7 年前
        1
  •  3
  •   klin    7 年前

    下一行和最后一行 只有在定义了排序顺序时才有意义。我假设排序顺序由 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;
    

    Live demo in rextester.