我正在尝试这样做......
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为null,则只将表连接到一个公共列上。 如果它不为空,那么它必须同时使用POS和SAC加入。
这可能吗?
答案 0 :(得分:4)
不要使用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
作为奖励,数据库引擎还可以在任一(或两个)表中使用pos
上的索引的优势。
答案 1 :(得分:1)
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
答案 2 :(得分:1)
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
我认为最后一次加入会使左连接前奏和内连接