连接的 "ON" 子句中的大小写

Case within join's "ON" caluse

我正在尝试做这样的事情...

SELECT lc.Location, count(h.empID) as 'Count', lu.LBL
FROM swam.lookup lu
    LEFT JOIN swam.empTable h
    ON CASE
        WHEN lu.sac is null 
            THEN lu.POS = h.POS
        ELSE (
            lu.POS = h.POS
            and
            lu.sac = h.sac)
    INNER JOIN swam.Locations lc
        ON h.LocationID = lc.LocationID
GROUP BY lc.Location, lu.LBL
ORDER BY lc.Location

因此,如果 lu.sac 为空,则仅在一个公共列上连接表。 如果不为空,则必须同时使用POS和SAC才能加入。

这可能吗?

不要使用 case。直接使用布尔逻辑即可:

FROM swam.lookup lu LEFT JOIN
     swam.empTable h
     ON lu.POS = h.POS AND
        (lu.sac is null OR lu.sac = h.sac) INNER JOIN
     swam.Locations fs
     ON h.LocationID = lc.LocationID

作为奖励,数据库引擎还可以 table 在任一(或两者)table 中利用 pos 上的索引。

    SELECT lc.Location, count(h.empID) as 'Count', lu.LBL
FROM swam.lookup lu
    LEFT JOIN swam.empTable h
    ON  (lu.sac is null  AND lu.POS = h.POS) OR  
                   not(lu.sac is null)  AND lu.POS = h.POS   and lu.sac = h.sac
    INNER JOIN swam.Locations fs
        ON h.LocationID = lc.LocationID
GROUP BY lc.Location, lu.LBL
ORDER BY lc.Location
SELECT lc.Location, count(h.empID) as 'Count', lu.LBL
FROM swam.lookup lu
LEFT JOIN swam.empTable h
  ON lu.POS = h.POS
 AND isnull(lu.sac, h.sac) = h.sac    
INNER JOIN swam.Locations fs
   ON h.LocationID = lc.LocationID  // this looks wrong lc is not defined
GROUP BY lc.Location, lu.LBL
ORDER BY lc.Location

而且我认为最后一个连接会变成左连接介绍和内部连接