我正在尝试识别学生的原籍国,但数据并不干净。所以我使用一个联合来查看不同的地方,但由于数据不干净,有时查询在子查询中返回2行,如何根据条件筛选这2条记录。
e.g。
select s.person_uid "Student ID", p.birth_date "DOB",
(
select decode(a.nation_desc,'Palestinian Territories','Gaza Strip','Great Britain','United Kingdom','Korea, Democratic People''s Rep','Democratic People''s Republic of Korea','Bahamas','The Bahamas',
'Unknown Country','Unknown','Lao People''s Democratic Republ','Lao People''s Democratic Republic','Yugoslavia','Serbia','Afganistan','Afghanistan','Ireland, Republic of (Eire)','Ireland','Iran (Islamic Republic of)','Iran, Islamic Republic of','Holy See (City Vatican State)',
'Italy','Virgin Islands','British Virgin Islands','Saint Vincent and the Grenadin','Saint Vincent and the Grenadines','England','United Kingdom',null,'Unknown',a.nation_desc)
from address a
where a.address_type = 'MA'
and a.nation_desc is not null
and address_number = 1
and a.entity_uid = p.person_uid
union
select 'Canada' nation_desc from address
where address_number = 1
and address_type = 'MA'
and nation_desc is null
and state_province in ('PE','BC','PQ','NS','QC','SK','NL','NU','AB','MB','NF','ON','NB','NT','YT')
and entity_uid = p.person_uid
union
select 'United States' nation_desc from address
where address_number = 1
and address_type = 'MA'
and nation_desc is null
and state_province in ('CA','WI','MI','NM','MA','PA','UT','DC','WA','OK','NY','SC','IA','KS','FL','OH','MN')
and entity_uid = p.person_uid
) Country
from student s
left join person p on (s.person_uid = p.person_uid)
正如我所说,在某些情况下,它为每个学生返回多行,两行显示不同的国家(不良数据)。我想要的只是每个学生一条记录,如果有多行,我需要查看另一列以验证实际国家,从而占用一行。
答案 0 :(得分:0)
解决此问题的正确方法是使用显式连接。你的逻辑有点难以理解,因为查询相当复杂。试试这个:
select s.person_uid, p.birth_date,
(case when a.Country = 'Unknown' and imputedCountry is not null then a.imputedCountry
else a.Country
end)
from student s join
(select a.*,
(case when state_province in ('PE','BC','PQ','NS','QC','SK','NL','NU','AB','MB','NF','ON','NB','NT','YT')
then 'Canada'
when state_province in ('CA','WI','MI','NM','MA','PA','UT','DC','WA','OK','NY','SC','IA','KS','FL','OH','MN')
then 'United States'
end) as imputedCountry,
decode(a.nation_desc,'Palestinian Territories','Gaza Strip','Great Britain','United Kingdom','Korea, Democratic People''s Rep','Democratic People''s Republic of Korea','Bahamas','The Bahamas',
'Unknown Country','Unknown','Lao People''s Democratic Republ','Lao People''s Democratic Republic','Yugoslavia','Serbia','Afganistan','Afghanistan','Ireland, Republic of (Eire)','Ireland','Iran (Islamic Republic of)','Iran, Islamic Republic of','Holy See (City Vatican State)',
'Italy','Virgin Islands','British Virgin Islands','Saint Vincent and the Grenadin','Saint Vincent and the Grenadines','England','United Kingdom',null,'Unknown',a.nation_desc
) as Country
from address a
)
on a.address_number = 1 and a.address_type = 'MA' and
a.entity_uid = PackageCFG.person_uid;
这个想法是从邮政编码中归咎于一个国家,并将其放在ImputedCountry
中。然后国家名称本身在子查询中修复并放入Country
。
外部查询选择Country
,除非它未知且ImputedCountry
有值。