查找一列值匹配而其他列不匹配的行

时间:2016-08-23 19:38:16

标签: sql sql-server

我有两张桌子A和B

表A

CODE TYPE
A 1
A 2
A 3
B 1
C 1
C 2

表B

CODE TYPE
A 1
A 2
A 4
B 2
C 1
C 3

我想返回CODE在两个表中的行,但是TYPE不是,而且两个表中的CODE都有多个TYPE,所以我的结果是

 CODE TYPE SOURCE
    A 3 Table A
    A 4 Table B
    C 2 Table A
    C 3 Table B

对此有何帮助?

3 个答案:

答案 0 :(得分:3)

我认为这涵盖了你的两个条件。

select code, coalesce(typeA, typeB) as type, src
from
    (
    select
        coalesce(a.code, b.code) as code,
        a.type as typeA,
        b.type as typeB,
        case when b.type is null then 'A' when a.type is null then 'B' end as src,
        count(a.code) over (partition by coalesce(a.code, b.code)) as countA,
        count(b.code) over (partition by coalesce(a.code, b.code)) as countB
    from
        A a full outer join B b
            on b.code = a.code and b.type = a.type
    ) T
where
        countA >= 2 and countB >= 2
    and (typeA is null or typeB is null)

答案 1 :(得分:2)

您可以使用full join查看代码是否匹配,并检查其中任何一个表格上的类型是否为null

select coalesce(a.code,b.code) code, coalesce(a.type,b.type) type,
case when b.type is null then 'A' when a.type is null then 'B' end src
from a
full join b on a.code = b.code and a.type = b.type
where a.type is null or b.type is null

要将结果限制为具有多种类型的代码,请使用

select x.code, coalesce(a.type,b.type) type,
case when b.type is null then 'Table A' when a.type is null then 'Table B' end src
from a
full join b on a.code = b.code and a.type = b.type
join (select a.code from a join b on a.code = b.code 
      group by a.code having count(*) > 1) x on x.code = a.code or x.code = b.code
where a.type is null or b.type is null
order by 1

答案 2 :(得分:0)

使用联合

with tu as (
    select CODE, TYPE, src='Table A'
    from TableA
    union all
    select CODE, TYPE, src='Table B'
    from TableB
)
select CODE, TYPE, max(src)
from tu t1
where exists (select 1 from tu t2 where t2.CODE=t1.CODE and t2.src=t1.src and t1.TYPE <> t2.TYPE)
group by CODE, TYPE
having count(*)=1
order by CODE, TYPE