Conditional DB2 SQL query
Lets Say I have a table called "Company", with a key of CompanyID There is another related table called "CompanyAddress", that has the CompanyID foreign key, so a join could be easily established.
This CompanyAddress table could have multiple addresses for a given company, say AddressType = 1, or AddressType = 2
The join etc to get the fields is trivial, however I want a conditional, where I query for addresses, and use AddressType = 1 if it is there, if it is not, use AddressType = 2
Currently, I am thinking of doing a union and removing duplicates but there has to be a be开发者_运维知识库tter way
It is actually pretty trivial to do this (if you are using DB2 for Linux/UNIX/Windows) by using OLAP functions. I've guessed at some of the column names in the companyAddress table, but the "magic" is in the rank() function:
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;
A Union and not exists test seems like the way to go for this
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)
The 2nd part uses left join so that companies that have neither address type 1 nor 2 will still show.
Either that, or use a left join to AddressType=2 that only fires when the first join (type=1) has failed.
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
As you can see, it is harder since each column from Address has to go through coalesce
between A and B.
精彩评论