SQL-比较不同表中的行

时间:2019-01-31 17:45:51

标签: sql compare

表1

Mem HCC2017     
--- -------
A   HCC19                   
A   HCC12               
B   HCC67                   
B   HCC132              
B   HCC190              
C   HCC88

D   HCC91

E   HCC20

表2

Member  HCC2018     
--- ---------
A   HCC14                   
A   HCC101              
A   HCC20               
A   HCC55               
B   HCC33

B   HCC131

我只想从表1中排除行:

  1. 两个年度中都有相同的HCC(例如,两个表中的MemberA都具有相同的HCC101)

  2. 表1.HCC2017中有HCC19,表2.HCC2018中有(HCC20或HCC21)(例如,成员A)

  3. 在Table1.HCC2017中有HCC132,而在Table2.HCC2018中有HCC131(例如,成员B)

结果数据集

A   HCC12               
A   HCC18   
B   HCC67                       
B   HCC190              
C   HCC88

D   HCC91

E   HCC20

我尝试以不同的方式使用case语句,但没有得到理想的结果。我不断深入兔子洞!

SELECT DISTINCT *
INTO #TEST
FROM
(
SELECT DISTINCT 
H7.MEMBER
,H7.HCC2017
,H8.HCC2018
,CASE  
WHEN H7.HCC2017 ='HCC19' AND H8.HCC2018 in ('HCC20','HCC21') THEN 1 
WHEN H7.HCC2017 ='HCC132' AND H8.HCC2018 ='HCC131' THEN 1 
WHEN H7.HCC2017 = H8.HCC2018 THEN 1

ELSE 0
END AS MATCH


FROM Table1 H7
LEFT JOIN Table2 H8 ON H7.MEMBER = H8.MEMBER
)A

WHERE MATCH = 0

SELECT DISTINCT * FROM #TEST

0 个答案:

没有答案