2016-07-11 35 views
1

比方說,我有這樣的表(這是簡化的,當然也有其他列):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.」

有什麼建議嗎?

+0

嘗試'COALESCE()',也許。 –

回答

1
SELECT a.OwnerKey, a.CompanyName, Case WHEN a.ContactType IS NULL THEN b.ContactType ELSE a.ContactType END AS ContactType 
FROM #TypeA a 
LEFT JOIN #TypeB b on a.OwnerKey = b.OwnerKey 
+0

簡短而甜美。我得到了我期待的結果,謝謝。 – Duston

1

我認爲這應該適合你。

with SortedResults as 
(
    select CompanyID 
     , ContactName 
     , ContactType 
     , ROW_NUMBER() over (partition by CompanyID order by ContactType) as RowNum 
    from ThisTable 
) 

select * 
from SortedResults 
where RowNum = 1 
0

試試這個SQL

Select t1.CompanyID , 
     ContactName = IIF(t1.ContactType='A',t1.ContactName,t2.ContactName) 
     ContactType = IIF(t1.ContactType='A','A',t2.ContactType) 
FROM address as t1 left join address as t2 
    on t1.CompanyID = t2.CompanyID 
    AND t1.ContactName = t2.ContactName 
    AND (t1.ContactType <> t2.ContactType) 

,如果你有更多的類型比A或B,你只想A和B在哪裏statment

WHERE (t1.ContactType = 'A' OR t1.ContactType = 'B') 
    AND (t2.ContactType = 'A' OR t2.ContactType = 'B') 
0

中添加此您定義的表中的列不會與示例查詢中的列匹配。我猜OwnerKey和CompanyID是一樣的嗎?

如果是這樣,你讓大部分的代碼的其餘部分,最後選擇將需要:

select * from #TypeA 
union all 
select * from #TypeB 
where not exists (
    select * 
    from #TypeA 
    where #TypeA.ownerkey = #TypeB.ownerkey) 
相關問題