简体   繁体   English

条件DB2 SQL查询

[英]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. 假设我有一个名为“Company”的表,其中包含CompanyID的密钥。还有另一个名为“CompanyAddress”的相关表,它具有CompanyID外键,因此可以轻松建立连接。

This CompanyAddress table could have multiple addresses for a given company, say AddressType = 1, or AddressType = 2 此CompanyAddress表可以具有给定公司的多个地址,例如AddressType = 1或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 获取字段的连接等是微不足道的,但我想要一个条件,我查询地址,如果它在那里使用AddressType = 1,如果不存在,使用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 一个联盟并不存在测试似乎是这样的方式

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. 第二部分使用左连接,因此仍然显示既没有地址类型1也没有地址类型2的公司。
Either that, or use a left join to AddressType=2 that only fires when the first join (type=1) has failed. 要么是这样,要么使用左连接到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

As you can see, it is harder since each column from Address has to go through coalesce between A and B. 正如您所看到的,由于Address中的每一列必须经过A和B之间的coalesce ,因此更难。

It is actually pretty trivial to do this (if you are using DB2 for Linux/UNIX/Windows) by using OLAP functions. 通过使用OLAP函数来实现这一点(如果您使用的是DB2 for Linux / UNIX / Windows)实际上非常简单。 I've guessed at some of the column names in the companyAddress table, but the "magic" is in the rank() function: 我已经猜到了companyAddress表中的一些列名,但是“magic”在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM