0
Table Schema

ID    Status     Patient
1     critical    Gabriel   
1     moderate   Frank
1     critical   Dorin 
2     low        Peter
3     critical    Noman 
3     moderate   Johnson

预期产出


ID   Patient1   Patient2
1    Gabriel    Dorin
3    Noman      Null

在这里,我只需要展示那些情况危急的病人。

我发现了类似的问题Multiple column values in a single row,但它在 SQL 中的列也是硬编码的。

谢谢!

4

2 回答 2

3

第一步是选择重症患者并对其进行排序:

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  ;

(这是给三个病人的。)

于 2013-04-30T11:11:48.913 回答
0

尝试构建查询并将结果执行到游标。

SET SERVEROUTPUT ON

DECLARE
v_fact NUMBER := 1;
v_max_cnt number:=1;
V_query CLOB:='';
BEGIN
select max(RNum) into v_max_cnt from(
  select row_number() over (partition by ID order by ID) RNum from PATIENTSTATUS where status='critical'
  )x;
FOR v_counter IN 1..v_max_cnt LOOP
  V_query := V_query||v_fact||' as Patient'||v_fact||(case when v_fact=v_max_cnt then '' else ',' end);
  v_fact:=v_fact+1;
  END LOOP;

  DBMS_OUTPUT.PUT_LINE  ('select * from (
    select id, patient, row_number() over (partition by id order by patient) as rnk
    from PATIENTSTATUS
    where status=''critical'')
    pivot (max(patient) for rnk in ('||V_query||'))
    order by 1;');
END;

从过程中,可以通过以下方式将数据插入游标

OPEN CUR_Your_Cursor FOR V_query;
于 2013-04-30T12:30:36.017 回答