Conditional DB2 SQL query

馋奶兔 提交于 2019-12-02 07:40:52

问题


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


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/4879832/conditional-db2-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!