sql - 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。我一步一步地写下我想要达到的目标,也许它会更容易理解;PRIORITY
VALUE1
ID
PRIORITY
= 2 有VALUE2
= 10,所以VALUE1
= 10,PRIORITY
= 3VALUE2
= 190,所以VALUE1
= 140,因为VALUE1
每列的总和ID
不能高于 150,PRIORITY
= 6 有VALUE2
= 90,但VALUE1
= 0,因为用= 3VALUE1
达到了值 150 。PRIORITY
在这种情况下,代码应该按比例ID
划分,可能会发生相同的“优先级”。VALUE2
解决方案
嗯。. . 我认为累积和一些比较:
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;
推荐阅读
- android - 如何检查表是否已存在
- java - 单击按钮时如何动态更改BorderPane中心的视图?
- html - 为什么我的导航栏图标没有出现在我的网站上?
- jupyter - JupyterLab 和 JupyterHub 有什么区别?
- google-app-engine - 网站托管在 App Engine 上,如何访问云存储中的图像?
- php - 使用 HTML2PDF 创建 A4 PDF 时出现 css top 属性问题
- java - 无法将战争文件部署到 Weblogic 12c 服务器上的特定文件夹
- c# - 如何在没有列名的情况下序列化 sql 数据?
- gradle - Gradle 子项目依赖项无法由需要它的项目解决
- javascript - (JavaScript & HTML )将项目从一个列表移动到另一个列表