一行多个类别

Multiple categories on one line

正在尝试识别 2 个组中的个人,在一行中显示此人的 ID 和两个组名。

尝试过 case 语句和连接,但它们出现在多行上。因此,一个 ID 会出现两次,一次针对一组,一次针对另一组。

select distinct
par.pid

from
participants par

where
par.participant_code = 'MEMBER'
and par.retirement in ('P', 'O')
and par.retirement_code in ('PS','AS', 'CP', 'EP')
group by par.pid
having count (*) > 1

上面的代码为我提供了我需要的所有个人,但是当我尝试显示他们所属的退休代码的名称时,每个 ID 得到 2 行。

尝试了这个并得到了重复的 ID 行:

Select distinct
AZ.pid,
 case when OT.retirement = 'P' then OT.retirement_code end Ar_Sys,
  case when OT.retirement = 'O' then OT.retirement_code end Ot_Sys

from
(select
par.pid

from
participants par

where
par.participant_code = 'MEMBER'
and par.retirement in ('P', 'O')
and par.retirement_code in ('PS','AS', 'CP', 'EP')
group by par.pid
having count (*) > 1) AZ,

(select
pa.pid,
pa.retirement,
pa.retirement_code

from
participants pa

where
pa.participant_code = 'MEMBER'
and pa.retirement in ('P', 'O')
and pa.retirement_code in ('PS','AS', 'CP', 'EP'))OT

where 
AZ.pid=OT.pid

您可以使用条件聚合:

select par.pid,
       max(case when retirement = 'P' then retirement_code end) Ar_Sys,
       max(case when retirement = 'O' then retirement_code end) Ot_Sys    
  from participants par    
 where par.participant_code = 'MEMBER'
   and par.retirement in ('P', 'O')
   and par.retirement_code in ('PS','AS', 'CP', 'EP')
 group by par.pid
having count (*) > 1

我会推荐 listagg():

select par.pid, listagg(par.retirement) within group (order by par.retirement) as retirements
from participants par
where par.participant_code = 'MEMBER' and
      par.retirement in ('P', 'O') and
      par.retirement_code in ('PS', 'AS', 'CP', 'EP') and
group by par.pid
having count(*) > 1;