在连接中使用条件

时间:2013-09-18 09:11:49

标签: sql sql-server sql-server-2008

我在3个表下面需要获取记录的地址。

1。地址AD  --->它具有所有地址值(addrline1,addrline2,state等)以及AddressID列

2。 Address_Employee AE  --->它具有EmpID,AddressID,AddressTypeID列 可以有多个具有不同AddressID和AddressTypeID值的EmpID的实例为3或1

第3。 Address_Type AT  --->有2行,包含AddressTypeID和AddressType列。带有1的AddressTypeID值将为Home,3将为Postal。

需要以这样的方式获取记录,首先需要查找邮政地址,如果没有,那么请回家。

我正在使用查询:

SELECT (AD.sAddressLine1+' '+AD.sAddressLine2+' '+AD.sSuburb+' '+AD.sPostCode) AS Address
from Address AD
INNER JOIN Address_Employee AE ON AD.AddressID = AE.AddressID 
INNER JOIN Address_Type AT ON AE.AddressTypeID= AT.AddressTypeID 

但是我怎样才能应用这个条件:“首先需要查找邮政地址,如果没有,那么请回家。”

请告知。

谢谢,克里希纳

1 个答案:

答案 0 :(得分:1)

您可以创建一个视图,为每个EmpID提供首选地址,并将其用于furthor连接。

Create View V_Emp_With_Preferred_Address as

Select Distinct EmpID
,Case when Exists(Select * from Address_Employee where Address_Employee.EmpID=e.EmpID and AddressTypeID=3) then
    ( -- take preferred postal address if available
     Select ISNULL(sAddressLine1+' ','')+ISNULL(sAddressLine2+' ','')+ISNULL(sSuburb+' ','')+ISNULL(sPostCode,'')
     from Address_Employee 
     join Address on Address.AddressID=Address_Employee.AddressID
     where Address_Employee.EmpID=e.EmpID and AddressTypeID=3
     )
else 
    (
     Select ISNULL(sAddressLine1+' ','')+ISNULL(sAddressLine2+' ','')+ISNULL(sSuburb+' ','')+ISNULL(sPostCode,'')
     from Address_Employee 
     join Address on Address.AddressID=Address_Employee.AddressID
     where Address_Employee.EmpID=e.EmpID and AddressTypeID=1
     )
end as Address
from dbo.Address_Employee e