树加入SQL查询

时间:2014-09-18 16:18:47

标签: sql db2

我必须通过只给父母作为输入来检索所有孩子。 示例I有一个表数据

TABLEA

LOAN_ID    CLIENT_ID
1          7
1          8
2          7
4          8
4          9
4         10
5          9
5         11
13        2
14        3

如果我只输入了CLIENT_ID = 7,则查询必须选择上表中除最后两列之外的所有列,因为 client_id 7具有1,2 LOAN_ID,并且在1中PRSN_ID 8具有loan_id = 4并且在该贷款中prsn_id 9再次具有5作为loan_id。

我们可以在没有存储过程的情况下为此编写SQL查询。

with temptbl (LOAN_ID, CLIENT_ID) as
( select 1 LOAN_ID, 7 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION
  select 1 LOAN_ID, 8 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION
  select 2 LOAN_ID, 7 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION 
  select 4 LOAN_ID, 8 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION
  select 4 LOAN_ID, 9 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION 
  select 4 LOAN_ID, 10 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION
  select 5 LOAN_ID, 9 CLIENT_ID FROM SYSIBM.SYSDUMMY1 UNION
  select 5 LOAN_ID, 11 CLIENT_ID FROM SYSIBM.SYSDUMMY1 ) 
  select * from temptbl;

0 个答案:

没有答案