I would like to join two tables and if columns do not match then another condition should be applied for joining the tables. Tables should join based on two products and level columns. If products match but level doesn’t match, then matching order should be Low > Med > High. For example, in Scenario 1, table 2 should match with Level Med (row 2) of table 1. If there is no “Med” level, then will match with “High” level. For example, in Scenario 2, table 2 should match with Level High (row 1) of table 1. If products do not match or level is NA then Value should be 0.
Here is the different scenarios of my problem. Table 1 is the master table and Table 2 can have different scenarios.
Table 1
ID Product_1 Product_2 Level Value
1 C D High 10
2 A B Med 11
3 A B High 12
4 B C Med 13
5 B C High 9
Different scenarios of Table 2
Scenario 1, Table 2
Product_1 Product_2 Level
A B Low
Expected Output
Product_1 Product_2 Level Value
A B Med 11
Scenario 2, Table 2
Product_1 Product_2 Level
C D Low
Expected Output
Product_1 Product_2 Level Value
C D High 10
Scenario 3, Table 2
Product_1 Product_2 Level
A B Med
Expected Output
Product_1 Product_2 Level Value
A B Med 11
Scenario 4, Table 2
Product_1 Product_2 Level
M N High
Expected Output
Product_1 Product_2 Level Value
M N High 0
Scenario 5, Table 2
Product_1 Product_2 Level
A B NA
Expected Output
Product_1 Product_2 Level Value
A B NA 0
The code I have tried, It basically matches, if not then return "0"
WITH `project.dataset.Table1` AS (
SELECT 1 ID, 'C' Product_1, 'D' Product_2, 'High' Level, 10 Value UNION ALL
SELECT 2, 'A', 'B', 'Med', 11 UNION ALL
SELECT 3, 'A', 'B', 'High', 12 UNION ALL
SELECT 4, 'B', 'C', 'Med', 13 UNION ALL
SELECT 5, 'B', 'C', 'High', 9
),
`project.dataset.Table2` AS (
SELECT 2 ID, 'A' Product_1, 'B' Product_2, 'Low' Level
),
-- The Above table idea is taken from Mikhail's solution
get_values as (
select
t1.ID
,t2.Product_1
,t2.Product_2
,t2.Level
,t1.Value
FROM `project.dataset.Table1` AS t1
join `project.dataset.Table2` t2 using(Product_1,Product_2,Level)
)
select t2.ID
,t2.Product_1
,t2.Product_2
,t2.Level
,IFNULL(Value, 0) as Value
from `project.dataset.Table2` t2
left join get_values gv on t2.ID = gv.ID
Thanks