我需要一个查询来获取没有客户联系人记录的客户端名称,如果有任何客户联系人,那么他们就会结束。请参阅下表结构。
表:客户
Client ID Client Name
-------------------------
1 John
2 Sean
3 Johnson
表: Client_Contact
Client Contact ID Client ID Start Date End Date
---------------------------------------------------------
1 1 1/1/1999 2/2/1999
2 1 1/2/1999 2/3/1999
3 1 1/3/1999 2/4/1999
4 2 1/2/2005 1/2/2007
5 2 1/3/2005 NULL
查询将返回 Johnson和Sean 。
提前感谢您的查询。
答案 0 :(得分:1)
试试..
select distinct cl.*
from Client cl
left outer join Client_Contact clcnt
on cl.[Client ID] = clcnt.[Client ID]
where (clcnt.[Client ID] IS NULL OR clcnt.[End Date] IS NULL)
答案 1 :(得分:1)
这是我用于此类查询的查询模式,与" left join"相比,可以带来显着的性能提升。模式,当涉及的表变得非常大时:
select c.[Client Name]
from Client c
where not exists
(
select *
from Client_Contact cc
where c.[Client ID] = cc.[Client ID]
and cc.[End Date] is null
)
答案 2 :(得分:0)
我希望此查询可能适合您
select c.* from client c
left join (select max([Client Contact ID]) ClientContactID,[Client ID] from client_contact
group by [client id]) ce on c.[Client ID]=ce.[Client ID]
left join client_contact ce1 on ce.[Client Contact ID]=ce1.[Client Contact ID]
where ce.[Client ID] is null
or ce1.[End Date] is not null