【问题标题】:Add value of type B to type A of same org_id将 B 类型的值添加到相同 org_id 的 A 类型
【发布时间】:2020-09-23 12:22:59
【问题描述】:
我有一张这样的桌子
ORG_ID TYPE VALUE
1 A 20
1 B 30
1 C 10
2 B 60
现在我想从这个表中为每个 org_id 选择值,键入但对于类型 A,我想将相同 org_id 的类型 B 的值添加到类型 A。我的查询应该返回这个
VALUE
50
30
10
60
在这种情况下,当 ORG_ID 为 1 且 TYPE 为 'A' 时,我必须添加该组织的 B 类值,即 30。但我不需要添加最后一个值,因为它属于另一个组织
【问题讨论】:
标签:
sql
oracle
plsql
sum
window-functions
【解决方案1】:
你可以使用窗口函数:
select t.*,
case when type = 'A'
then value + max(case when type = 'B' then value else 0 end) over(partition by org_id)
else value
end as new_value
from mytable t
Demo on DB Fiddle:
ORG_ID |类型 |价值 | NEW_VALUE
-----: | :--- | ----: | --------:
1 |一个 | 20 | 50
1 |乙| 30 | 30
1 | C | 10 | 10
2 |乙| 60 | 60
【解决方案2】:
左连接应该可以完成这项工作:
SELECT a.id, a.type, a.value + COALESCE(b.value, 0)
FROM mytable a
LEFT JOIN mytable b ON a.type = 'A' AND b.type = 'B' AND a.org_id = b.org_id