2014-03-25 60 views
0

我有以下字段的賬戶表中的所有子記錄:科目#,姓名返回與父母

和子表CFALTN與字段:cfseq,cfaal1,CFACC#

我要查詢和鏈接主要在下面的例子中所有子記錄:

TABLE1 
Acct#, Name 
2244, Joe 
1890, Jack 
0223, Sam 
9898, Mary 

TABLE2 
cfseq, cfaal1, cfacc# 
1, Joe and bens farm, 2244 
2, POD mary and ben, 2244 
1, POD Jay Williams, 1890 
1, POD Ronnie future farm, 0223 
2, for raising goats, 0223 
1, OR James Russell, 9898 

我想,來查詢POD的嬰兒被發現,但不只是返回具有POD子記錄,但都子記錄。

SELECT T1.acct#, T1.name, T2.cfseq, T2.cfaal1, T2.cfacc# 
FROM data.table1 T1 
    JOIN data.table2 T2 WHERE T1.acct# = T2.cfacc# 
AND T2.cfaal1 like '%POD%' 

DESIRED RESULTS: 
2244, Joe, 1, Joe and bens farm, 2244 
2244, Joe, 2, POD mary and ben, 2244 
1890, Jack, 1, POD Jay Williams, 1890 
0223, Sam, 1, POD Ronnie future trust, 0223 
0223, Sam, 2, for education wing, 0223 

回答

1
SELECT T1.acct#, T1.name, T2.cfseq, T2.cfaal1, T2.cfacc# 
FROM data.table1 T1 
JOIN data.table2 T2 ON T1.acct# = T2.cfacc# 
where 
    T1.acct# in (select cfacc# from T2 where cfaal1 like '%POD%')