sql中的按比例分配

omqzjyyz  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(497)

我有一个包含位置及其整数分配的sql表。随着总体分配的增加,基础分配需要按比例增加,同时抵消任何舍入误差。

我试过的是:

new_distribution=new_alloc-ROUND(NVL(SUM(original distribution) OVER (PARTITION BY location rows between unbounded preceding and 1 PRECEDING),0)*(new_alloc/original alloc),0) as num

不过,总数与40人不符。如何在sql/redshift/oracle中实现这一点,使新发行版接近原始发行版,而总数达到40?

csga3l58

csga3l581#

您可以通过截断值来分配值,然后将剩余的值分配给某些行。这看起来像:

select t.*,
       (trunc_new_dist + (case when seqnum <= new_alloc - total_trunc_new_dist then 1 else 0 end)
       ) as new_dist
from (select t.*,
             trunc(new_alloc * orig_dist) / orig_alloc as trunc_new_dist,
             sum( trunc(new_alloc * orig_dist) / orig_alloc ) over () as total_trunc_new_dist,
             row_number() over (order by location) as seqnum
      from t
     ) t

相关问题