這裏的結果。然後加入到你的數據是做到這一點的一種方式,使用row_number()
分析函數並且不需要任何連接,顯式或隱式。它還處理各種特殊情況:既沒有郵寄地址也沒有家庭地址(但仍然需要在輸出中顯示)的學生,以及具有兩個郵寄地址的另一名學生(在這種情況下,隨機選擇一個);如果有喜歡一個到另一個,查詢可以很容易地適應,以適應)。
with
students (id, name, address_type, address) as (
select 11, 'Andy', 'home' , '123 X street' from dual union all
select 11, 'Andy', 'office' , 'somewhere else' from dual union all
select 15, 'Eva' , 'mailing', 'post office' from dual union all
select 18, 'Jim' , 'office' , '1 building' from dual union all
select 30, 'Mary', 'mailing', 'mail addr 1' from dual union all
select 30, 'Mary', 'office' , '1 building' from dual union all
select 30, 'Mary', 'home' , 'her home' from dual union all
select 30, 'Mary', 'mailing', 'mail addr 2' from dual
)
-- End of test data (not needed for the SQL query - reference your actual table)
select id, name, address_type,
case when address_type is not null then address end as address
from (
select id, name,
case when address_type in ('home', 'mailing')
then address_type end as address_type,
address,
row_number() over (partition by id
order by case address_type when 'mailing' then 0
when 'home' then 1 end) as rn
from students
)
where rn = 1
;
ID NAME ADDRESS_TYPE ADDRESS
--- ---- ------------ --------------
11 Andy home 123 X street
15 Eva mailing post office
18 Jim
30 Mary mailing mail addr 1
4 rows selected.
請添加您的示例輸入和預期輸出 – GurV
學生可以有多個家庭住址(或多個郵寄地址)嗎?如果是這樣,應該選擇什麼?另外,保證每個學生至少有一個家或郵寄地址?如果不是,該爲學生顯示什麼? – mathguy