根据 SQL 中的子项更新父项

Update parent based on child in SQL

我有一个 table 格式如下:

parent child exists
1234 2345 true
1234 3436 true
1234 4355 true
1234 0 false
1234 0 false

我想编写一个查询来选择和更新 table 如果特定父项的所有非零子项都存在 = True。如果是这样的话,我想将“0”子项的所有存在设置为 'true'

即使非零子项的一个值为假,零子项也应保持 'false'。

这是我尝试过的:

select item,child,
case when child = 0 and exists = 'False' 
and item in (SELECT item 
FROM table t1 
where not EXISTS
( SELECT t2.item 
    FROM table t2
    WHERE t2.item = t1.item and t2.child = t1.child  
    and t2.child <> 0
    and t2.exists = 'True'
  )) 
  then 'True' else exists end exists from (SELECT *
    FROM table 
) 

你只需要一个相关的子查询。

select * from dclee.test1 t1;

Update dclee.test1 t1
  set t1."EXISTS" = 'true'
    
    where t1.child = 0 
    and not exists (select 1 from dclee.test1 t2
                    where t1.parent = t2.parent 
                        and t2.child  0 
                        and t2."EXISTS" = 'false')
           and exists (select t3.parent, count(1) nz_cnt
                       from dclee.test1 t3
                       where t1.parent = t3.parent
                       and t3.child != 0
                       group by t3.parent
                       having count(1) > 0);
                        
commit;
            
drop table dclee.test1;

create table dclee.test1 as
select 1234 as Parent, 0 as child, 'false' as "EXISTS" from dual
union all
select 1234 as Parent, 2345 as child, 'true' as "EXISTS" from dual
union all 
select 1234 as Parent, 3436 as child, 'true' as "EXISTS" from dual
union all
select 1234 as Parent, 4355 as child, 'true' as "EXISTS" from dual
union all
select 1235 as Parent, 0 as child, 'false' as "EXISTS" from dual
union all
select 1235 as Parent, 5345 as child, 'true' as "EXISTS" from dual
union all 
select 1235 as Parent, 6436 as child, 'true' as "EXISTS" from dual
union all
select 1235 as Parent, 3436 as child, 'false' as "EXISTS" from dual
union all
select 1236 as Parent, 0 as child, 'false' as "EXISTS" from dual
union all
select 1236 as Parent, 0 as child, 'false' as "EXISTS" from dual