比方說,我有這樣的表(這是簡化的,當然也有其他列):T-SQL返回一行如果其他行不存在
CompanyID (int)
ContactName (varchar(50))
ContactType (char(1))
與價值觀:
CompanyID | ContactName | ContactType
-----------------------------------------------
1 | John Doe | A
1 | Jane Smith | B
2 | Ralph Jones | B
3 | Dick Grayson | A
我想要的是所有的公司有一個ContactType ='A',除非沒有ContactType ='A'返回ContactType ='B'。所以在這個例子中,我想:
1, John Doe (because he's a ContactType A)
2, Ralph Jones (because Company #2 doesn't have a ContactType A)
3, Dick Grayson (because he's a ContactType A)
我不能只說「A或B」,因爲一家公司可能同時擁有這兩個。
這是我嘗試過什麼(失敗)
use MyFancyDatabase
drop table #TypeA
drop table #TypeB
drop table #TypeAB
create table #TypeA(ownerkey int, ContactName varchar(200), ContactType char(1))
insert #TypeA
Select ownerkey, ContactName, ContactType from address
where ContactType = 'A' and CancelDate is null
create table #TypeB(ownerkey int, ContactName varchar(200), ContactType char(1))
insert #TypeB
Select ownerkey, ContactName, ContactType from address
where ContactType = 'B' and CancelDate is null
create table #TypeAB(ownerkey int, ContactName varchar(200), ContactType char(1))
insert #TypeAB
select * from #TypeA
except
select * from #TypeB
我猜英語是「A,但如果沒有A,然後採取B.」
有什麼建議嗎?
嘗試'COALESCE()',也許。 –