oracle-跨行分布一行值

t9eec4r0  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(301)

如附件所述。我需要将“b”列中的值分配为小于或等于a列。现在对于a>b的情况2,我需要65的分布为44,16,5,但是得到44,16,20。

yzckvree

yzckvree1#

sql表表示无序集。但是你的结果假设是有序的。我将假设有一个排序列,并将其表示为 ? .
这是一个累加和问题——用算术:

select t.*,
       (case when b >= running_a then a
             when b >= running_a - a then b - (running_a - a)
             else 0
        end) as new_a
from (select t.*, sum(a) over (order by ?) as running_a
      from t
     ) t

这是一把小提琴。

ylamdve6

ylamdve62#

我就是这样理解这个问题的。

SQL> with test (a, b) as
  2  -- sample data
  3    (select 0, 60 from dual union all
  4     select 88, 0 from dual union all
  5     select 32, 0 from dual union all
  6     select 7,  0 from dual
  7    ),
  8  -- query you need begins here
  9  temp as
 10    (select a,
 11            max(b) over (order by null) b
 12     from test
 13    )
 14  select
 15    x.a,
 16    case when x.a = 0 then y.b
 17         else case when x.a > y.b then y.b
 18              else x.b
 19         end
 20    end b
 21  from test x left join temp y on x.a = y.a
 22  order by x.a;

         A          B
---------- ----------
         0         60
         7          0
        32          0
        88         60

SQL>
SQL> with test (a, b) as
  2  -- sample data
  3    (select 0, 75 from dual union all
  4     select 21, 0 from dual union all
  5     select 12, 0 from dual union all
  6     select 42, 0 from dual
  7    ),
  8  -- query you need begins here
  9  temp as
 10    (select a,
 11            max(b) over (order by null) b
 12     from test
 13    )
 14  select
 15    x.a,
 16    case when x.a = 0 then y.b
 17         else x.a
 18    end b
 19  from test x left join temp y on x.a = y.a
 20  order by x.a;

         A          B
---------- ----------
         0         75
        12         12
        21         21
        42         42

SQL>

相关问题