我的表格有4列,分别由两组(ID_PROCESSO, ID_INSTANCIA_BPM)
和(ID_INSTANCIA_BPM_PAI, ID_PROCESSO_PAI)
隔开。
如果第二组(ID_INSTANCIA_BPM_PAI AND ID_PROCESSO_PAI)
为null
,并且该记录的第一组不作为记录的第二组,其中ID_PROCESSO == ID_PROCESSO_PAI
,则必须将其返回。
如果第二组(ID_INSTANCIA_BPM_PAI AND ID_PROCESSO_PAI)
是not null
和ID_PROCESSO <> ID_PROCESSO_PAI
,则必须将其返回。
对于sqlfiddle示例,返回值应遵循类似的规则
#|ID_PROCESSO|ID_INSTANCIA_BPM|ID_INSTANCIA_BPM_PAI|ID_PROCESSO_PAI
1 3 2957 (null) (null) --Returned
2 5 2958 2957 3 --Returned
3 4 2960 (null) (null) --Returned
4 4 2975 (null) (null) --Returned
5 3 2976 (null) (null) --Removed by #10
6 3 2977 (null) (null) --Removed by #9
7 5 2978 2977 3 --Removed by #8
8 5 2979 2978 5 --Returned
9 3 2980 2977 3 --Returned
10 3 2981 2976 3 --Returned
11 4 2984 (null) (null) --Returned
所以结果必须是:
#|ID_PROCESSO|ID_INSTANCIA_BPM|ID_INSTANCIA_BPM_PAI|ID_PROCESSO_PAI
1 3 2957 (null) (null) --Returned
2 5 2958 2957 3 --Returned
3 4 2960 (null) (null) --Returned
4 4 2975 (null) (null) --Returned
8 5 2979 2978 5 --Returned
9 3 2980 2977 3 --Returned
10 3 2981 2976 3 --Returned
11 4 2984 (null) (null) --Returned
http://sqlfiddle.com/#!18/32c86/1
有人知道只有选择才能做到这一点,还是我需要一个游标才能实现此结果?
答案 0 :(得分:0)
如果我理解您说的没错,
select *
from processes p1
where (p1.ID_INSTANCIA_BPM_PAI is null AND p1.ID_PROCESSO_PAI is null
and
not exists (select *
from processes p2
where p2.ID_INSTANCIA_BPM_PAI = p1.ID_INSTANCIA_BPM
and p2.ID_PROCESSO_PAI = p1.ID_PROCESSO
and p2.ID_PROCESSO = p1.ID_PROCESSO)
)
or
(p1.ID_INSTANCIA_BPM_PAI is not null AND ID_PROCESSO_PAI is not null
and
not exists (select *
from processes p2
where p2.ID_INSTANCIA_BPM_PAI = p1.ID_INSTANCIA_BPM
and p2.ID_PROCESSO_PAI = p1.ID_PROCESSO
)
)
在sqlfiddle的输入行中,您错过了1行:
insert into processes values (5, '2979', '2978', 5);