内部联接基于SQL Server 2008中的列值

时间:2014-12-05 17:42:33

标签: sql sql-server sql-server-2008 tsql inner-join

我想基于列值

加入两个表
  • 如果pm.ServiceLevelID值为1或NULL,那么u.FacilityId上的内部联接
  • 如果pm.ServiceLevelID值为2,则u.FacilityServiceId
  • 上的内部联接

这两个表pm, u包含以下列:

ProviderMessages
  MessageID, FacilityServiceID, ServiceLevelID, FacilityID, ProviderTypeID

User_FA
  FacilityServiceId, UserFacilityID, FacilityId

目前,我有INNER JOIN

SELECT DISTINCT 
    MessageID, UserFacilityID, 9    
FROM 
    #ProviderMessages   
INNER JOIN 
    #User_FA ON (#User_FA.FacilityId = #ProviderMessages.FacilityID OR  
                                   #ProviderMessages.FacilityID IS NULL)
             AND (#User_FA.FacilityServiceId = #ProviderMessages.FacilityServiceID)

4 个答案:

答案 0 :(得分:0)

SELECT DISTINCT MessageID, UserFacilityID, 9    
 FROM #ProviderMessages   
 JOIN #User_FA 
   ON #ProviderMessages.ServiceLevelID  in (null,1,2) 
  and (  ( #ProviderMessages.ServiceLevelID  in (null,1) 
           and #User_FA.FacilityId = #ProviderMessages.FacilityID) 
         or 
         ( ProviderMessages.ServiceLevelID = 2
           AND #User_FA.FacilityServiceId = #ProviderMessages.FacilityServiceID) 
      ) 

答案 1 :(得分:-1)

这是您的查询,使用表别名使其更具可读性:

SELECT DISTINCT MessageID, UserFacilityID, 9    
FROM #ProviderMessages m INNER JOI
     #User_FA u
    ON (u.FacilityId = m.FacilityID OR m.FacilityID IS NULL) AND
       u.FacilityServiceId = m.FacilityServiceID;

你想要的逻辑是

SELECT DISTINCT MessageID, UserFacilityID, 9    
FROM #ProviderMessages m INNER JOIN
     #User_FA u
    ON ((pm.ServiceLevelID = 1 or pm.ServiceLevelID is null) AND pm.FacilityId = u.facilityId) or
       (pm.ServiceLevelID = 2 and pm.FacilityServiceID = m.FacilityServiceID)

答案 2 :(得分:-1)

我不确定我是否理解得很好,但在我之前的工作中,我们遇到了类似的情况。 请试试这个:

SELECT DISTINCT 
    MessageID, UserFacilityID, 9    
FROM 
    #ProviderMessages   
    INNER JOIN #User_FA 
        ON (CASE WHEN ISNULL(#ProviderMessages.ServiceLevelID, 1) = 1
                 THEN #ProviderMessages.FacilityID
                 ELSE #ProviderMessages.FacilityServiceId
            END)
            = (CASE WHEN ISNULL(#ProviderMessages.ServiceLevelID, 1) = 1
                 THEN #User_FA.FacilityId
                 ELSE #User_FA.FacilityServiceId
              END)

我希望它有所帮助。

答案 3 :(得分:-2)

联合两个结果


SELECT DISTINCT MessageID, UserFacilityID, 9    
FROM #ProviderMessages   
INNER JOIN #User_FA ON (#User_FA.FacilityId = #ProviderMessages.FacilityID OR  
                                   #ProviderMessages.FacilityID IS NULL)
WHERE #ProviderMessages.ServiceLevel <> 2

UNION

SELECT DISTINCT MessageID, UserFacilityID, 9    
FROM #ProviderMessages   
INNER JOIN #User_FA ON (#User_FA.FacilityServiceId = #ProviderMessages.FacilityServiceID)
WHERE #ProviderMessages.ServiceLevel = 2