I need to perform left outer join on the same table. As a result I expect all requested columns from table 1 and only those from table 2 which joined.
Here is how to reproduce:
drop table nz_mri_survey_agg;
create table mri_survey_agg (
HOUSEHOLD_PERSON_HK integer,
MRI_DICTIONARY_ID INTEGER,
rank integer);
insert into mri_survey_agg values (651694412, 2127115057, 36903);
insert into mri_survey_agg values (647638311, 1293574238, 35413);
insert into mri_survey_agg values (647638311, -2076426274, 35413);
insert into mri_survey_agg values (651694412, -2076426274, 35413);
insert into mri_survey_agg values (651694412, -2051582071, 35411);
insert into mri_survey_agg values (647638311, -1747375415, 35613);
insert into mri_survey_agg values (647638311, 1234567, 35610);
Here is the query:
select distinct t1.household_person_hk, t2.mri_dictionary_id
from mri_survey_agg t1
left outer join (
select household_person_hk, mri_dictionary_id from mri_survey_agg
where mri_dictionary_id in
(-2076426274, -2051582071, -1747375415)) t2
on t1.household_person_hk = t2.household_person_hk;
I expect the next output:
household_person_hk mri_dictionary_id
651694412 -2051582071
647638311 -2076426274
651694412 -2076426274
647638311 -1747375415
647638311 <NaN>
The output is:
household_person_hk mri_dictionary_id
651694412 -2051582071
647638311 -2076426274
651694412 -2076426274
647638311 -1747375415
It works perfect on Postgres, but doesn't give me expected results on Redshift.
Appreciate for any hints.
UPD : Actually, the actual output is correct!
I just ran your code on Postgres and it returns four rows, which is correct. Here is a SQL Fiddle, which is now working.
Note that your query can more easily be written as:
select distinct t1.household_person_hk, t2.mri_dictionary_id
from mri_survey_agg t1 left outer join
mri_survey_agg t2
on t1.household_person_hk = t2.household_person_hk and
t2.mri_dictionary_id in (-2076426274, -2051582071, -1747375415);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.