【问题标题】:Conditional DB2 SQL query条件 DB2 SQL 查询
【发布时间】:2011-02-02 21:03:14
【问题描述】:

假设我有一个名为“Company”的表,键为 CompanyID 还有另一个名为“CompanyAddress”的相关表,它具有 CompanyID 外键,因此可以轻松建立连接。

这个 CompanyAddress 表可以有给定公司的多个地址,比如 AddressType = 1 或 AddressType = 2

获取字段的连接等很简单,但是我想要一个条件,在其中查询地址,如果存在则使用 AddressType = 1,如果不存在,则使用 AddressType = 2

目前,我正在考虑进行联合并删除重复项,但必须有更好的方法

【问题讨论】:

    标签: sql db2


    【解决方案1】:

    通过使用 OLAP 函数来实现这一点实际上非常简单(如果您使用的是 DB2 for Linux/UNIX/Windows)。我已经猜到了 companyAddress 表中的一些列名,但“魔法”在 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;
    

    【讨论】:

      【解决方案2】:

      Union and not exists 测试似乎是解决这个问题的方法

      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
      

      如您所见,这更难,因为 Address 中的每一列都必须在 A 和 B 之间通过 coalesce

      【讨论】:

        猜你喜欢
        • 2020-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 2016-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多