您正在尋找地址的優先級。大多數數據庫支持窗口/分析功能,並提供一個機制:
select p.first_name, a.address_1, a.zip, a.state
from person p join
(select a.*,
row_number() over (partition by a.person_id
order by (case when a.address_type = 'T' then 1
when a.address_type = 'M' then 2
when a.address_type = 'R' then 3
end)
) as seqnum
from addresses a
) a
on p.person_id = a.person_id and seqnum = 1;
編輯:
如果你想要一個給定類型的所有地址,只需切換row_number()
到dense_rank()
:
select p.first_name, a.address_1, a.zip, a.state
from person p join
(select a.*,
dense_rank() over (partition by a.person_id
order by (case when a.address_type = 'T' then 1
when a.address_type = 'M' then 2
when a.address_type = 'R' then 3
end)
) as seqnum
from addresses a
) a
on p.person_id = a.person_id and seqnum = 1;
你使用什麼數據庫? –