September 8, 2015 at 6:37 am
If this has been asked, please excuse me.
I need to join 2 tables but the join needs to account for 2 seperate columns.
for example:
select
a. type
a. prod_code
a. prod_type
b. division
from table1 a
left join table2 b
on a. prod_code = b. prod_code
and a. prod_type = b. prod_type
The issue is that you may have only the prod_code or prod_type and null value for the other in table1.
Ideally I want it to check for both then if 1 isn't available then it draws the division of the available. having both or one or the other determines the division it falls under.
Is this possible?
Thanks in advance.
edit for spelling...
September 8, 2015 at 6:43 am
Try
left join table2 b on a. prod_code = b.prod_code or a. prod_type = b. prod_type
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
September 8, 2015 at 8:12 am
Thanks Gila.
This still brings back more records than the original :S
September 8, 2015 at 8:52 am
September 8, 2015 at 2:24 pm
Really not much more advice I can offer without having some data to work with.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
September 11, 2015 at 11:02 am
As stated by others, it's not very clear what it is your trying to accomplish...
On the off chance that I did correctly understand the requirement, give the following a try.
SELECT
a.type,
a.prod_code,
a.prod_type,
b.division
FROM
table1 a
LEFT JOIN table2 b
ON a.prod_code = COALESCE(b.prod_code,a.prod_code)
AND a.prod_type = COALESCE(b.prod_type,a.prod_type)
AND (b.prod_code IS NOT NULL OR b.prod_type IS NOT NULL) ;
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply