我有一个包含许多列的表:(以前的帖子每一个source_id仅具有一个id,但是这种情况下每一个source_id具有多个id)
id col1 source_id
a1 765.3 a5
a2 3298.3 a4
a3 8762.1 a8
a4 3298.3 (null)
a5 (null) a6
a6 (null) (null)
a7 10 a5
我想用null values of source _id
填充values from id
。例如,必须将source_id a5 row has null
替换为id a1 + id a7 values
,然后将source_id a6 row having null
替换为a5 row
输出:
id col1 source_id
a1 765.3 a5
a2 3298.3 a4
a3 8762.1 a8
a4 3298.3 (null)
a5 765.3+10=775.3 a6
a6 765.3+10=775.3 (null)
a7 10 a5
谢谢!
编辑:
为了更清楚,需要填充source_id和id以外的其他列中的空值。仅给出col1来简化发布,可能还会有很多列
这样的操作将为您提供在source_id列中具有引用而在col1列中具有值的行。
但是要根据上一行的上一次计算来计算下一行...我不确定仅使用select语句会如何...
select id
, case when col1 is null then
(select sum(col1) from test tt where tt.sourceid = t.id)
else
col1
end result
, sourceid
from test t
order by id;
当数据中有两个问题时,这是一个选项:
with cte as (select t.id
, case when t.col1 is null then
(select sum(tt.col1) from test tt where tt.sourceid = t.id)
else
t.col1
end result
, t.sourceid
from test t
order by id)
select t.id
,
case when t.result is null then
(select sum(tt.result) from cte tt where tt.sourceid = t.id)
else
t.result
end result
, t.sourceid
from cte t
order by id
使用相关的层次查询(您可以在id
列或ROWID
伪列上进行关联:]
SELECT id,
COALESCE(
col1,
(
SELECT SUM( COALESCE( col1, 0 ) )
FROM table_name s
START WITH s.ROWID = t.ROWID
CONNECT BY source_id = PRIOR id
)
) AS col1,
source_id
FROM table_name t;
因此,对于您的示例数据:
CREATE TABLE table_name ( id, col1, source_id ) AS
SELECT 'a1', 765.3, 'a5' FROM DUAL UNION ALL
SELECT 'a2', 3298.3, 'a4' FROM DUAL UNION ALL
SELECT 'a3', 8762.1, 'a8' FROM DUAL UNION ALL
SELECT 'a4', 3298.3, null FROM DUAL UNION ALL
SELECT 'a5', null, 'a6' FROM DUAL UNION ALL
SELECT 'a6', null, null FROM DUAL UNION ALL
SELECT 'a7', 10, 'a5' FROM DUAL;
此输出:
ID | COL1 | SOURCE_ID:-| -----:| :--------a1 | 765.3 | a5a2 | 3298.3 | a4a3 | 8762.1 | a8a4 | 3298.3 | nulla5 | 775.3 | a6a6 | 775.3 | nulla7 | 10 | a5
db <>小提琴here