여러 열이있는 테이블이 있습니다. (이전 게시물에는 하나의 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
source _id의 null 값
을 id의 값
으로 채우고 싶습니다.예를 들어, source_id a5 row has null
이 값은 id a1 id a7 values
로 대체되어야하며,이어서 source_id a6 row with null
이 대체되어야합니다. a5 행
포함
산출:
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 이외의 열에 있는 null 값을 채워야 합니다. 단순화된 게시물에 대해 col1 만 주어지면 많은 열이 있을 수 있습니다.
상관 된 계층 적 쿼리를 사용합니다 (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 | a5
a2 | 3298.3 | a4
a3 | 8762.1 | a8
a4 | 3298.3 | null
a5 | 775.3 | a6
a6 | 775.3 | null
a7 | 10 | a5
계층 구조의 각 분기에서 널이 아닌 첫 번째 값을 찾으면 반복을 중지해야 할 수 있습니다. 간단한 필터만 추가하면됩니다.
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
AND PRIOR col1 IS NULL
)
) AS col1,
source_id
FROM table_name t;
(출력은 위와 동일합니다.)
db < > fiddle 여기
다음 선택은 source_id 열에 참조가 있고 col1 열에 값이있는 행을 제공합니다.
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
여기에 데모가 있습니다