一行中有多行列多列

时间:2013-04-30 10:55:37

标签: sql oracle

Table Schema

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

预期OutPut


ID   Patient1   Patient2
1    Gabriel    Dorin
3    Noman      Null

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

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

谢谢!

2 个答案:

答案 0 :(得分: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  ;

(这是针对三名患者的。)

答案 1 :(得分: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;