-1

I have two tables say, A and B of account_numbers. B being a subset of A. How do I join the two tables such that I add an additional field in the output table with the common elements (here account_numbers) being flagged as 1 and rest 0

Table A
Account_Number
11
13
15
16
17
20

Table B
Account_Number
13
16
20

Output Table    
Account Flag
11  0
13  1
15  0
16  1
17  0
20  1
Aleks G
  • 56,435
  • 29
  • 168
  • 265
SouravD
  • 127
  • 1
  • 12

3 Answers3

3

I think the best way to approach this is with a left outer join:

select a.account_number,
       (case when b.account_number is null then 0 else 1 end) as flag
from A left outer join
     B
     on A.account_number = b.account_number;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Gordon this too works fine. Helped in clarifying some doubts. Thank you and Yang both for your help. – SouravD Jul 24 '13 at 00:00
  • @Yang's solution is quite clever. On the other hand, this will generally make better use of indexes, be faster, retains duplicates in table A, and allows you to easily include more columns from with `A` or `B`. – Gordon Linoff Jul 24 '13 at 00:03
  • Yes, I too had this question; if there were more columns probably count(*)-1 won't work. But then Yang's was extremely clever and was precise to my query. Thanks again @Gordon – SouravD Jul 24 '13 at 00:10
2

Try an outer join instead of group by and union all, it will perform much bettter, particularly with large tables.

select a.account_number
  , case 
      when b.account_number is not null then 1
      else 0
    end as flag
from a, b
where a.account_number *= b.account_number
jmarkmurphy
  • 11,030
  • 31
  • 59
1
SELECT account_number, COUNT(*)-1 AS flag
FROM (
  SELECT account_number FROM A
    UNION ALL
  SELECT account_number FROM B
) AB
GROUP BY account_number;

Checkout this demo. Let me know if it works.

Yang
  • 7,712
  • 9
  • 48
  • 65