Skip to content
Advertisement

SQL Two joins; First one a left join; second only join when combination does not exist yet

I have the following problem. I have the following 3 tables, I can’t edit those. I have a “main” table I would like to join “Table1” to, I succeeded (see fiddle). The next step is to join “Table2”, but only when the Charge-Name combination does not exist yet. If it doesn’t exists add it and set Factor to 0. See table “Desired result” for my goal.

http://sqlfiddle.com/#!9/fc7409/1

Code:

Tables:

Advertisement

Answer

You can try to use a subquery to UNION ALL two result sets, one is made from Main join Table1 another is made from Main join Table2.

Table2 need to write a column for Factor be 0

Then use the aggregate function to get your result.

Query 1:

Results:

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