首页 > 解决方案 > oracle 优先分配价值

问题描述

我有这样的桌子:

    | VALUE1 | VALUE2 | ID | PRIORITY |
    |-------|--------|----|----------|
    | 150   | 190    | 1  | 3        |
    | 150   | 90     | 1  | 6        |
    | 150   | 10     | 1  | 2        |

我想要这样的桌子:

    | VALUE1 | VALUE2 | ID | PRIORITY |
    |-------|--------|----|----------|
    | 140   | 190    | 1  | 3        |
    | 0     | 90     | 1  | 6        |
    | 10    | 10     | 1  | 2        |

我需要找出一个 PL/SQL 代码,它从列中分配VALUE2优先级VALUE1。在我的示例中始终相同,它是一个数字150。我一步一步地写下我想要达到的目标,也许它会更容易理解;PRIORITYVALUE1ID

  1. PRIORITY= 2 有VALUE2= 10,所以VALUE1= 10,
  2. PRIORITY= 3 VALUE2= 190,所以VALUE1= 140,因为VALUE1每列的总和ID不能高于 150,
  3. PRIORITY= 6 有VALUE2= 90,但VALUE1= 0,因为用= 3VALUE1达到了值 150 。PRIORITY

在这种情况下,代码应该按比例ID划分,可能会发生相同的“优先级”。VALUE2

标签: sqloracle

解决方案


嗯。. . 我认为累积和一些比较:

select t.*,
       (case when sum(value2) over (order by priority) - value2 < value1
             then value1
             when sum(value2) over (order by priority) > value1
             then 0
             else value1 - sum(value2) over (order by priority)
        end) as allocated_value
from t

您还可以使用greatest()andleast()使逻辑更加复杂:

select greatest(least(value1 - sum(value2) over (order by priority), value2), 0)
from t;

推荐阅读