如果存在,请选择首选地址,否则选择“工作”地址

时间:2014-09-30 01:23:16

标签: sql sql-server tsql

我有3张桌子:

PeopleAffiliation: Affiliationid, peopleid, addressid
Addresses: addressid, addresstypeid, address, city, state, zip, preferredaddress (bit)
AddressTypes: addresstypeid, addresstypeconst

我需要选择地址为首选地址的所有人员地址,但如果没有首选地址,那么我必须显示地址,其中addresstypeconst ='工作'

我无法弄清楚如何做到这一点。有谁知道我怎么能做到这一点?

以下是我想要完成的一个示例:

Affiliationid,peopleid,addressid

    1           1          1
    2           1          2
    3           2          3
    4           2          4

addressid,addresstypeid,...,preferredaddress(bit)

   1          3                 1  
   2          5                 0
   3          1                 0
   4          5                 0

addresstypeid,addresstypeconst

 1                  Home
 2                  mail
 3                  shipping
 5                  Work

期望结果

Affiliationid,peopleid,addressid

    1             1         1
    4             2         4    (showing work address as user doesn't have a preferred one)

1 个答案:

答案 0 :(得分:0)

这应该做:

 SELECT * 
FROM   peopleaffiliation pa 
       LEFT OUTER JOIN addresses addr 
                    ON pa.addressid = addr.addressid 
       LEFT OUTER JOIN addresstypes addtyp 
                    ON addtyp.addresstypeid = addr.addresstypeid 
WHERE  (addr.preferredaddress = 1 )
        OR( COALESCE(addr.preferredaddress, 0) = 0 
           AND addtyp.addresstypeconst = 'Work' )