如何返回另一个表中不存在的行

时间:2015-03-25 19:28:45

标签: sql-server tsql

我有一张像这样的表A:

CompanyID | SectionID | Service Name
------------------------------------
    1     |     1     |   AAAAAAA
    1     |     2     |   BBBBBBB 
    2     |     1     |   CCCCCCC

和表格b如下:

  InspectionID | CompanyID | SectionID
  -------------------------------------    
        1      |    1      |     2
        2      |    2      |     1

我想要一个SQL命令,它返回没有相关检查的每个服务名称(来自表a)(表{B加CompanyIDSectionID

就像那样:

Service Name
------------ 
 BBBBBBB

谢谢!

2 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT distinct [Service name]
FROM tableA a
left join tableb b on a.companyId = b.companyId
    and a.sectionId = b.sectionId
where b.companyId is null

select distinct [Service name]
from tablea a
where not exists (
    select 1
    from tableb b
    where a.companyId = b.companyId
        and a.sectionId = b.sectionId
)

答案 1 :(得分:2)

select a.[Service name]
from a
left join b on a.companyID = b.companyID
           and a.sectionID = b.sectionID
group by a.[Service name]
having sum(case when b.InspectionID is not null then 1 end) = 0