如何只选择满足多个有序条件之一的行

时间:2014-06-12 15:05:21

标签: sql oracle

我的客户有多个地址。每个客户/地址组合在数据库(Oracle)表中都有自己的行。

我正在尝试进行查询,如果客户有“主要地址”,我只显示主要地址, 否则如果他有发货地址,我只显示发货地址, 否则,如果他有一个“辅助地址”,我会显示辅助地址, 否则我什么都没显示。

此顺序非常重要,问题是数据库中的条目没有特定的顺序,这意味着可能会发现同一个客户首先有一个发货地址,后来有一个主地址。因此,我不需要满足其中一个条件的第一行...

我尝试了这个,但它返回每行的结果,例如一个人的多个结果:

CASE WHEN ADR = 'MAIN' THEN 'MAIN'
         WHEN ADR = 'SHIPMENT' THEN 'SHIPMENT' 
         WHEN ADR = 'SECONDARY' THEN 'SECONDARY' 
         ELSE null
    END AS Adressart

澄清一下,输入内容如下:

CUSTOMER_NR ADDRESS_TYPE
1           SHIPMENT
1           MAIN
2           SHIPMENT
3           SECONDARY
3           SHIPMENT
4           SECONDARY

结果如下:

CUSTOMER_NR ADDRESS_TYPE
1           MAIN
2           SHIPMENT
3           SHIPMENT
4           SECONDARY

2 个答案:

答案 0 :(得分:0)

我认为您可以对地址表使用多个联接,并使用coalesce仅返回订单中的一个地址

查询看起来像:

SELECT      customer_nr, coalesce(a1.address, a2.address, a3,address) AS address
FROM        customer AS c 
LEFT JOIN   address AS a1 where a1.customer_nr = c.customer_nr and a1.address_type = 'MAIN'
LEFT JOIN   address AS a2 where a2.customer_nr = c.customer_nr and a2.address_type = 'SHIPMENT'
LEFT JOIN   address AS a3 where a3.customer_nr = c.customer_nr and a3.address_type = 'SECONDARY'

答案 1 :(得分:0)

以下查询可以获得所需的结果:

SELECT
  CUSTOMER_NR,
  ADDRESS_TYPE
FROM
(
  select 
  customer_nr,
  address_type,
  row_number () over (partition by customer_nr order by 
                      case address_type
                        when 'MAIN' then 1
                        when 'SHIPMENT' then 2
                        when 'SECONDARY' THEN 3
                        else 4
                      end) rn
from addresses
)
WHERE rn = 1;

首先,使用带CASE语句的优先级对地址进行排序。然后,仅选择具有rn = 1(最高优先级的地址类型)的地址类型。

SQL Fiddle demo