如何有条件地从多个地址中选择一个地址

时间:2019-04-09 06:38:01

标签: sql sql-server

我有这样的桌子:

CustomerID | Address  | Address Type
100000001  | addressA | Mailing Address
100000001  | addressB | Registered Address
100000001  | Null.    | Office Address

一个客户可能有多个地址。在这种情况下,我只想选择一个地址:

  1. 如果Office Address不为null,那么我将从Office Address获取Address。如果“办公室地址”为空,则转到数字2。

  2. 检查注册地址是否不为空,然后从注册地址中获取地址。

3 个答案:

答案 0 :(得分:1)

在有条件的情况下将TOP 1ORDER BY一起使用

select top 1 *
from   address
where  CustomerID = @CustomerID
and    Address is not null
order by case when AddressType = 'Office' then 1
              when AddressType = 'Registered' then 2
              else 3
              end

答案 1 :(得分:1)

CREATE TABLE CUSTOMER (CUSTOMERID INT , ADDRESS VARCHAR(500) , ADDRESSTYPE VARCHAR(25));

INSERT INTO CUSTOMER VALUES (100000001,'ADDRESSA' ,'MAILING ADDRESS');
INSERT INTO CUSTOMER VALUES (100000001,'ADDRESSB',  'REGISTERED ADDRESS');
INSERT INTO CUSTOMER VALUES (100000001, NULL ,'OFFICE ADDRESS');

SELECT 
    ISNULL(
        (SELECT ADDRESS FROM CUSTOMER WHERE CUSTOMERID = 100000001 AND ADDRESSTYPE = 'OFFICE ADDRESS' ) ,
        (SELECT ADDRESS FROM CUSTOMER WHERE CUSTOMERID = 100000001 AND ADDRESSTYPE = 'REGISTERED ADDRESS' )
    ) 

答案 2 :(得分:0)

select * from customer 

select  max(customerID) customerID ,max(Address) Address ,max(Addresstype) Addresstype
from customer  
where address is not null
group by customerID

输出

enter image description here