SQL选择记录在两个字段中匹配的位置

时间:2017-03-08 00:29:30

标签: sql db2

表:A

acctno,ratcod,ssno

仅选择ssno相同的记录,ratcod包含6,7,8中的任何一个,并且在其他地方找到相同的ssno以包含ratcod值<> -6,7,8-

数据表A

acctno ratcod ssno
123456 6      123-44-5566
23456  4      123-44-5566
12345  1      123-44-5566
654321 6      333-44-5566
664433 6      222-44-5566
222336 2      123-44-5566
554646 4      444-98-9876

期望的输出

acctno ratcod ssno
123456 6      123-44-5566
23456  4      123-44-5566
12345  1      123-44-5566
222336 2      123-44-5566

尝试以下操作会产生错误 DB2 for i5 / OS] SQL0199 - 不期望关键字IN。

select tableA.* 
    from (select ssno from refdat1.lnmast lnmast 
    group by lnmast.ssno 
    having sum(case ratcod in (6, 7 ,8) then 1 else 0 end) > 0 
    and sum(case ratcod in (6, 7, 8) then 0 else 1 end) > 0) 
    as ASum 
JOIN tableA 
ON tableA.ssno = ASum.ssno

1 个答案:

答案 0 :(得分:0)

逻辑是:找到所有ssnos中有一个ratcod(6,7,8)并且没有ratcod(6,7,8)。找到这些后,返回带有ssno的所有行。

select tableA.*
from (select ssno
      from tableA
      group by ssno
      having sum(case ratcod in (6, 7, 8) then 1 else 0 end) > 0
      and sum(case ratcod in (6, 7, 8) then 0 else 1 end) > 0) 
      as ASum
JOIN TableA 
ON TableA.ssno = ASum.ssno