I need to make the inner join of two tables, however, wanted to know how can I resolve this situation:
If the field in the second table is NULL he do inner join with another field.
Can you give me an example?
Thanks
I need to make the inner join of two tables, however, wanted to know how can I resolve this situation:
If the field in the second table is NULL he do inner join with another field.
Can you give me an example?
Thanks
depends what you are trying to achieve...
CREATE TABLE #X
(
[Id] INT,
[Name] VARCHAR(100)
)
INSERT INTO #X VALUES
(1,'michaeljackson'),
(2,'jim'),
(3,'jill'),
(4,'j')
CREATE TABLE #Y
(
[Id] INT,
[AlternateId] INT,
[Score] INT
)
INSERT INTO #Y VALUES
(1,1,10),
(2,2,20),
(3,3,30),
(4,4,40),
(NULL,2,50)
--will join all of the records in #x to the null record
SELECT *
FROM #X x
INNER JOIN #Y y
ON
x.Id = COALESCE(y.Id,x.Id)
--will join just to the ID = 4 record
SELECT *
FROM #X x
INNER JOIN #Y y
ON
x.Id = COALESCE(y.Id,4)
--redirect and let join use alternative field
SELECT *
FROM #X x
INNER JOIN #Y y
ON
x.Id = COALESCE(y.Id,y.AlternateId)
--maybe you want to actually do a FULL OUTER JOIN!
SELECT *
FROM #X x
FULL OUTER JOIN #Y y
ON
x.Id = y.Id
Easiest is probalby to consider the second table as two disjoint tables like this:
select *
from a
join (
select NewKey = key1, * from b where b.key1 is null
union all
select NewKey = key2, * from b where b.key1 is not null
) b on b.NewKey = a.key
I believe the following should work adequately.
SELECT *
FROM tblA a
INNER JOIN tblB b ON (b.Col1 IS NOT NULL AND b.Col1 = a.Col1) OR (b.Col1 IS NULL AND b.Col2 = a.Col2)
If b.Col1 is not NULL then it joins on Col1, otherwise if it is NULL then it joins on Col2.
Try this:
select * from a
inner join b on
(case when b.columntojoin is null then b.alternatecolumn else b.columntojoin end)
= a.columntojoin