您可以使用一個case語句和聚合得到一個固定的字符串:
case when count(c.c_id) > 1 then 'Multiple Records' else max(c.char_val) end
和您需要按r_id
和name
進行分組:
select r.r_id, r.name,
case when count(c.c_id) > 1 then 'Multiple Records'
else max(c.char_val) end as char_val
from records r
join char c on r.r_id = c.r_id
group by r.r_id, r.name
order by r.r_id;
我也切換到使用ANSI連接,而不是舊的語法(如@Thorsten建議)。
這是一個使用CTE來生成你的數據,讓他們稍微不同的名稱,因爲char
是保留字演示:
with t_records (r_id, name) as (
select 1, 'A' from dual
union all select 2, 'B' from dual
union all select 3, 'C' from dual
),
t_char (c_id, r_id, char_val) as (
select 1, 3, 'c1' from dual
union all select 2, 1, 'c2' from dual
union all select 3, 1, 'c3' from dual
union all select 4, 2, 'c3' from dual
)
select r.r_id, r.name,
case when count(c.c_id) > 1 then 'Multiple Records'
else max(c.char_val) end as char_val
from t_records r
join t_char c on r.r_id = c.r_id
group by r.r_id, r.name
order by r.r_id;
R_ID N CHAR_VAL
---------- - ----------------
1 A Multiple Records
2 B c3
3 C c1
您可以用'listagg'用於此目的 – Rahul
你不應該使用20世紀80年代聯接了。改用適當的ANSI連接('從記錄r連接字符r.R_ID = c.R_ID')。 –