表的简单聚合/连接

时间:2013-07-23 23:29:53

标签: sql

我有两个表,分别是account_numbers的A和B. B是A的子集。如何连接两个表,以便在输出表中添加一个附加字段,其中公共元素(此处为account_numbers)标记为1,其余为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

3 个答案:

答案 0 :(得分:3)

我认为解决此问题的最佳方法是使用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;

答案 1 :(得分:2)

尝试使用外连接而不是group by和union all,它会执行更多的操作,特别是对于大型表。

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

答案 2 :(得分: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;

结帐this demo。如果有效,请告诉我。