如何获取表 A 的记录,该记录位于表 B 中的一行中


SELECT ClaimID, CPTCode FROM TABLEA
ClaimId CPTCode
  **60  62000**
  **60  0213T**
  60    99383
  60    93230
  60    96372
SELECT cpt1,CPT2 FROM TABLEB
cpt1    CPT2
**62000 0213T**
**62000 0230T**
62000   0216T
62000   0228T

仅从表 A 中选择表B中同一行的记录结果应该是

60  62000
60  0213T

我认为这可以满足您的需求:

select ClaimID, CPTCode 
from tablea a
where exists (select 1
              from tableb b
              where b.cpt1 = a.cptcode
             ) or
      exists (select 1
              from tableb b
              where b.cpt2 = a.cptcode
             );

此查询可以利用两个索引:tableb(cpt1)tableb(cpt2)

您可以将其编写为:

select ClaimID, CPTCode 
from tablea a
where exists (select 1
              from tableb b
              where a.cptcode in (b.cpt1, b.cpt2)
             );

但是,此版本更难优化。

试试这个-

select obj.ClaimID, obj.CPTCode from (
select row_number() as row_noA, ClaimID, CPTCode FROM TABLEA
join 
select row_number() as row_noB, cpt1,CPT2 FROM TABLEB
on TABLEA.CPTCode = TABLEB.CPT2 and TABLEA.row_noA = TABLEB.row_noB
)obj

连接两个表并使用相同的行号匹配每行并获得输出

最新更新