'Redshift Target Table Equijoin Predicate Error with Subquery
I am trying to run an update statement using a subquery to apply logic to the target table before updating. I keep getting the following error (below) even though the target table equijoin is specified in the where clause. Is there something I'm missing? I've also tried converting the subquery into a CTE which results in the same error. The "stg" alias table contains the same amount of rows as the "tgt" so it's not there is a mismatch there.
Error: SQL Error [XX000]: ERROR: Target table must be part of an equijoin predicate
SQL:
update db.target_table as tgt
set
ind = stg.ind_stg
,ts = current_timestamp
from
(
select
load_date
,val_a
,val_b
,stdev.val_a_stdev
,stdev.val_b_stdev
,rec_updated_ts
,case
when (load_date >= 'XXXXX' and load_date <= 'XXXXXX')
or (abs(val_a) >= stdev.val_a_stdev
or abs(val_b) >= stdev.val_b_stdev)
then True else False end as ind
from db.target_table
cross join
(
select
cast(stddev_samp(val_a) as dec(14,2))*2.0 val_a_stdev
,cast(stddev_samp(val_b) as dec(14,2))*2.0 val_b_stdev
from db.target_table
where load_date <= (current_date - 2)
) as stdev
where load_date <= (current_date - 2)
) stg
where stg.load_date = tgt.load_date
However, if I was to wrap the "stg" subquery as a temp table, then ran the same update statement (below), it works. This is perplexing because the original error points towards the target table, but only changing the method of how the subquery is derived fixes the query. Not sure I understand what is going on...
update db.target_table as tgt
set
ind = stg.ind_stg
,ts = current_timestamp
from <SAME STAGE LOGIC> as stg
where stg.load_date = tgt.load_date;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
