I need some help handling null columns in joins. I have three tables (below are just examples) Map, Employee and Region. Primary table is Map where I join Employee table on the MapID column to get employeeID and Employee table is used to join with Region table on employeeID.
Requirement: for any given mapID, check if there are any region for EmployeeID. If there is a match, pick it. Only if EmployeeID is null, then check for zip5 and pick the region.
I tried the code shown here; for mapID = 7890, it returns region for both EmployeeID Null and 200. For this mapid, there exists employeeID = 200, and only this value should be returned, ignoring the other.
For mapID = 4567, employeeID is null and correct value is being picked.
Can anyone tell me what my mistake is?
Expected output:
| mapid | Prodcode | proddesc | amount | zip5 | region |
|---|---|---|---|---|---|
| 7890 | 23458 | POT | 1234789 | 45678 | West S San Diago |
Actual output:
| mapid | Prodcode | proddesc | amount | zip5 | region |
|---|---|---|---|---|---|
| 7890 | 23458 | POT | 1234789 | 45678 | West S San Diago |
| 45678 | 7890 | 23458 | POT | 1234789 | West So. CA |
DROP TABLE IF EXISTS #map
CREATE TABLE #map
(
zip5 varchar(10),
mapid varchar(10),
Prodcode int,
proddesc varchar(10),
amount float
)
DROP TABLE IF EXISTS #employee
CREATE TABLE #employee
(
EmployeeID varchar(10),
mapid varchar(10)
)
DROP TABLE IF EXISTS #Region
CREATE TABLE #Region
(
mapid varchar(10),
EmployeeID varchar(10),
zip5 varchar(10),
Region varchar(50)
)
INSERT INTO #map
SELECT '04987', '9879', 24567, 'ISC', '17645.00'
UNION
SELECT '45678', '7890', 23458, 'POT', '1234789.00'
UNION
SELECT '56333', '5678', 24567, 'MHT', '23400.00'
UNION
SELECT '00899', '4567', 24567, 'PIT', '1234.00'
UNION
SELECT '00899', '3457', 24567, 'ISC', '17645.00'
INSERT INTO #employee
SELECT '100', '9879'
UNION
SELECT '200', '7890'
UNION
SELECT '400', '5678'
UNION
SELECT NULL, '4567'
UNION
SELECT '500', '3457'
INSERT INTO #Region
SELECT '9879', '100', '04987', 'South'
UNION
SELECT '7890', '200', '45678', 'West S San Diago'
UNION
SELECT '7890', NULL, '45678', 'West So. CA'
UNION
SELECT '5678', '400', '56333', 'EastCentral'
UNION
SELECT '4567', NULL, '00899', 'south'
SELECT * FROM #employee WHERE mapid = '7890'
SELECT * FROM #map WHERE mapid = '7890'
SELECT * FROM #Region WHERE mapid = '7890'
SELECT DISTINCT
m.*, region
FROM
#map m
LEFT JOIN
#Region r ON r.mapid = m.mapid
LEFT JOIN
#employee e ON e.mapid = m.mapid
AND r.employeeid = ISNULL(e.employeeid, '')
OR (r.employeeid <> ISNULL(e.employeeid, '')
AND r.zip5 = m.zip5)
WHERE
m.mapid = '7890'
left join #employee e on e.mapid=m.mapid and (r.employeeid=isnull(e.employeeid,'') OR (r.employeeid<>isnull(e.employeeid,'') and r.zip5=m.zip5))so that thee.mapid=m.mapidcondition is always taken into account, regardless of everything that follows.