条件null替换

qco9c6ql  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(305)

我有一个包含许多列的表:(上一篇文章中每个源id只有一个id,但本例中每个源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 _idvalues 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\u id和id之外的列中的空值。对于简化的post,只有col1,可能也有很多列

uhry853o

uhry853o1#

使用相关层次查询(您可以在 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<>在这里摆弄

dba5bblo

dba5bblo2#

下一个select将为您提供那些在source\u 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

这是一个演示

相关问题