Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 join depending on column value

Author  Topic 

sqlclarify
Yak Posting Veteran

56 Posts

Posted - 2009-04-22 : 21:45:06
Hello,

I have a table A. I want to join table B (and get col b) if a column b in table B is not null, else join table C and get col c).

What is the best way to do this?

If I left join both table B and C won't I get a different number of rows than what I would get if I join only table B and table C depending on what needs to be joined?



nathans
Aged Yak Warrior

938 Posts

Posted - 2009-04-22 : 22:13:25
Ok, lets start with a test setup and see if we can zero in on what you are after. What would u like to return if no match in B or C (as reflected in 4A below)

declare @A table (id int, n varchar(10))
declare @B table (id int, n varchar(10))
declare @C table (id int, n varchar(10))

insert into @A
select 1, '1A' union select 2, '2A' union
select 3, '3A' union select 4, '4A'

insert into @B
select 1, '1B' union select 3, '3B'

insert into @C
select 2, '2C'


select a.id, a.n,
coalesce(b.n, c.n)
from @A a
left
join @B b on a.id = b.id
left
join @C c on a.id = c.id


Nathan Skerl
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2009-04-23 : 04:30:24
You haven't said if there is a 1 to 1 relationship between the three tables.

If there is a 1 to many between A and B and a 1 to 1 between A and C then that makes this a little more complicated.

If it's 1 to 1 then you can do what you want by just LEFT JOINING b and c to a and then using a CASE statement in your SELECT list.


Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
Go to Top of Page

sqlclarify
Yak Posting Veteran

56 Posts

Posted - 2009-04-23 : 20:56:02
If there is no match in B or C I need to return null.

Yes, the problem is that the relationship between A and B is one to many and the relationship between A and C is one to many (from what I can understand). They have not explicitly stated whether the relationship between these tables is one-to-one or one-to-many. I assume it is one-to-many because if it was one-to-one these tables would still be one single table right?
Go to Top of Page

sqlclarify
Yak Posting Veteran

56 Posts

Posted - 2009-04-24 : 23:21:45
Anybody have any advice?
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2009-04-24 : 23:34:28
please provide some sample data and the expected result


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -