Reputation: 3
I need a Result Table as:
Metric_Data with the following conditions being met:
How do you generate this 3rd table? I have tried all kinds of joins - full, left, right, etc.
Upvotes: 0
Views: 222
Reputation: 107696
select
A.LocID,
A.Prod_ID,
B.Metric_ID,
coalesce(C.Metric_Data + D.Metric_Data, C.Metric_Data, D.Metric_Data) Metric_Data
from (
select LocID, Prod_ID from table1 group by LocID, Prod_ID) A
inner join (
select LocID, Metric_ID from table1 group by LocID
union
select LocID, Metric_ID from table2 group by LocID) B on A.LocID = B.LocID
left join table1 C on C.LocID = A.LocID and C.Prod_ID = A.Prod_ID and C.Metric_ID = B.Metric_ID
left join table2 D on D.LocID = A.LocID and D.Metric_ID = B.Metric_ID
Notes:
select
coalesce(a.LocID, b.LocID) LocID,
a.Prod_ID,
coalesce(a.Metric_ID, b.Metric_ID) Metric_ID,
coalesce(a.Metric_Data + b.Metric_Data, a.Metric_Data, b.Metric_Data) Metric_Data
from table1 a
full outer join table2 b
on a.LocID = b.LocID and a.Metric_ID = b.Metric_ID
This assumes
Upvotes: 1