我有这样的桌子:
CustomerID | Address | Address Type
100000001 | addressA | Mailing Address
100000001 | addressB | Registered Address
100000001 | Null. | Office Address
一个客户可能有多个地址。在这种情况下,我只想选择一个地址:
如果Office Address不为null,那么我将从Office Address获取Address。如果“办公室地址”为空,则转到数字2。
检查注册地址是否不为空,然后从注册地址中获取地址。
答案 0 :(得分:1)
在有条件的情况下将TOP 1
与ORDER 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)