第一步是选择危重病人,并命令他们:
select id, patient, row_number() over (partition by id order by patient) as rnk
from your_table
where status='critical';
此之后,你可以用这种方式选择前两个危重病人:
select id,
max(case when rnk=1 then patient end) as Patient1,
max(case when rnk=2 then patient end) as Patient2
from (
select id,
patient,
row_number() over (partition by id order by patient) as rnk
from your_table
where status='critical'
)
group by id;
如果你想有一个更灵活的解决方案你可以尝试像下面这样的查询,但是你应该在运行前选择排名数:
with your_table as
(select 1 as id, 'critical' as status, 'Gabriel' as patient from dual
union all
select 1, 'moderate', 'Frank' from dual union all
select 1, 'critical', 'Dorin' from dual union all
select 1, 'critical', 'Vasile' from dual union all
select 2, 'low', 'Peter' from dual union all
select 3, 'critical', 'Noman' from dual union all
select 3, 'moderate', 'Johnson' from dual)
select * from (
select id, patient, row_number() over (partition by id order by patient) as rnk
from your_table
where status='critical'
)
pivot (max(patient) for rnk in (1, 2, 3))
order by 1 ;
(这是针对三位患者的)
如果你有3名危重病人在同一个ID,会发生什么被插入到光标? – 2013-04-30 11:06:23
@AmitSingh我认为你没有看到这个问题,并预期的结果.. :) – BreakHead 2013-04-30 11:08:13
你是对的,我现在得到它 – 2013-04-30 11:11:56