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 better way
A Union and not exists test seems like the way to go for this
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.
As you can see, it is harder since each column from Address has to go through
coalesce
between A and B.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: