Skip to content
Advertisement

SQL – Add in a new table join when all left join – Total beginner [closed]

I need help with adding in an additional join to my query.

All the tables are currently left outer joined from SO_Header however there is also some data I need from a table called RANGE which only links to the MODEL table.

How can I edit my script to bring in the RANGE table?

I’m using the get data from microsoft query in Excel.

Extract from my script:

FROM dbo.SO_HEADER SO_HEADER LEFT OUTER JOIN 
     dbo.WEEK_NUMBERS WEEK_NUMBERS 
     ON SO_HEADER.SOH_Build_Week = WEEK_NUMBERS.WEEK_Week_No AND
        SO_HEADER.SOH_Build_Year = WEEK_NUMBERS.WEEK_Year LEFT OUTER JOIN
     dbo.MODEL MODEL 
     ON SO_HEADER.SOH_Model = MODEL.MODEL_Code LEFT OUTER JOIN
     dbo.RETAILERS RETAILERS 
     ON SO_HEADER.SOH_Retailer = RETAILERS.RET_Code LEFT OUTER JOIN
     dbo.FACTORY_OPTIONS FACTORY_OPTIONS 
     ON SO_HEADER.SOH_Upholstery = FACTORY_OPTIONS.FAC_Code LEFT OUTER JOIN
     dbo.FINANCE_HOUSES FINANCE_HOUSES 
     ON SO_HEADER.SOH_Finance = FINANCE_HOUSES.FIN_Code

Advertisement

Answer

Assuming you have a foreign key in your range table with named RANGE_MODEL_Code then you can join model and range like this

Also you can change the way you wants to join the table (i-e let join, inner join or outer join) depends on your business requirement

FROM dbo.SO_HEADER SO_HEADER LEFT OUTER JOIN 
     dbo.WEEK_NUMBERS WEEK_NUMBERS 
     ON SO_HEADER.SOH_Build_Week = WEEK_NUMBERS.WEEK_Week_No AND
        SO_HEADER.SOH_Build_Year = WEEK_NUMBERS.WEEK_Year LEFT OUTER JOIN
     dbo.MODEL MODEL 
     ON SO_HEADER.SOH_Model = MODEL.MODEL_Code LEFT OUTER JOIN
     dbo.RANGE RANGE
     ON MODEL.MODEL_Code = RANGE.RANGE_MODEL_Code LEFT OUTER JOIN
     dbo.RETAILERS RETAILERS 
     ON SO_HEADER.SOH_Retailer = RETAILERS.RET_Code LEFT OUTER JOIN
     dbo.FACTORY_OPTIONS FACTORY_OPTIONS 
     ON SO_HEADER.SOH_Upholstery = FACTORY_OPTIONS.FAC_Code LEFT OUTER JOIN
     dbo.FINANCE_HOUSES FINANCE_HOUSES 
     ON SO_HEADER.SOH_Finance = FINANCE_HOUSES.FIN_Code

Change your table name and joining keys from both table i-e RANGE_MODEL_Code and MODEL_Code according to your schema

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement