My merge into
cannot run because the 'on' condition does not identify a one-to-one correspondence between the tables. I would like to solve this by asking that, only on such rows where the condition fails, the value of a third column is used to decide.
merge into A using B
on (A.id = B.id and A.date between B.startdate and B.enddate)
when matched then update set
A.foo = B.foo
-- where B.tiecondition = 1 *
* this is not good because it operates always, while I want to use the condition only when there are multiple matches for the main "merge on" condition. This happens since, for some B.id rows, subsequent [B.startdate, B.enddate] intervals actually overlap (i.e. more than one B.foo values is possible for a given A.date). In these cases, the column B.tiecondition would allow me to make a choice among the possible matches.
I suppose the 'on' clause might be modified with something like
on (
(A.id = B.id and A.date between B.startdate and B.enddate)
or (A.id = B.id and (A.date between B.startdate and B.enddate) and B.tiecondition = 1)
)
but I am not sure whether I would get the correct result or if there is a more elegant way to do this.
Perhaps I could use a left join
instead, and add a couple of conditions checking when there are multiple matches in the results and keeping only the rows satisfying to the condition, but this looks a bit cumbersome too.