2011-02-02 118 views
1

讓我們說我有一個名爲「Company」的表,其中有一個CompanyID的密鑰 還有另一個名爲「CompanyAddress」的相關表,它具有CompanyID外鍵,因此可以輕鬆建立聯接。有條件的DB2 SQL查詢

該公司地址表中可以有一個給定公司的多個地址,說的AddressType = 1,或地址類型= 2

的加盟等,以獲得該領域是微不足道的,但是我希望有一個條件,我在那裏查詢地址,並使用地址類型= 1,如果它的存在,如果沒有,用的AddressType = 2

目前,我想這樣做工會和刪除重複的,但必須有一個更好的辦法

回答

2

它實際上是非常容易做到這一點(如果您正在使用DB2 Linux版/ UNIX/Windows)通過使用OLAP函數。我已經猜到了公司地址表中的一些列名稱,但「魔術」在rank()函數中:

with preferredAddresses as (
    select 
     companyID, 
     address, 
     addresstype, 
     rank() over (partition by companyID order by addresstype) as rank 
    from 
     companyAddress 
) 
select * 
from 
    company C, 
    inner join preferredAddresses A 
     on c.companyID = A.companyID 
where 
    A.rank = 1; 
+0

+1這將與DB2 for IBM i V5R4 – 2011-02-03 16:19:33

2

一個聯盟而不存在測試似乎是這樣的方式去

select * 
from company C 
inner join CompanyAddress A on A.companyID = C.companyID 
where A.AddressType = 1 
union all 
select * 
from company C 
LEFT join CompanyAddress A on A.companyID = C.companyID 
    and A.AddressType = 2 
    and not exists (
    select * 
    from CompanyAddress B 
    where B.companyID = C.companyID 
     and B.AddressType = 1) 

第二部分使用左連接,以便既沒有地址類型1也沒有2的公司仍將顯示。
要麼是這樣,要麼使用左連接來AddressType = 2,只有當第一個連接(type = 1)失敗時纔會觸發。

select C.*, 
    coalesce(A.addressType, B.addressType) addressType, 
    coalesce(A.streetname, B.streetname) streetname 
from company C 
left join CompanyAddress A on A.companyID = C.companyID and A.AddressType = 1 
left join CompanyAddress B on A.companyID is null 
    AND B.companyID = C.companyID and B.AddressType = 2 

正如你所看到的,這是很難,因爲從地址每一列都必須經過​​3210 A和B之間