select record_time,ward_code,ward_name,bed_no,patient_id,pat_name,fall,fall_damage,drop_bed,lost,suicide,pipeline_slippage,other,result
from(
select case when cnt > 1 and rn = 1 then null else id end id,record_time,ward_code,ward_name,bed_no,patient_id,pat_name,
fall,fall_damage,drop_bed,lost,suicide,pipeline_slippage,other,result
from(
select row_number() over(partition by id,patient_id order by record_time) rn,
count(*) over(partition by id,patient_id) cnt,
id,record_time,ward_code,max(ward_name) ward_name,max(bed_no) bed_no,patient_id,max(pat_name) pat_name,
max(decode(section_name,'事件',decode(record,'跌倒','1',null),null)) as fall,
max(decode(section_name,'事件',decode(record,'摔伤','1',null),null)) as fall_damage,
max(decode(section_name,'事件',decode(record,'坠床','1',null),null)) as drop_bed,
max(decode(section_name,'事件',decode(record,'走失','1',null),null)) as lost,
max(decode(section_name,'事件',decode(record,'自杀','1',null),null)) as suicide,
max(decode(section_name,'管道名称',decode(record,null,null,1),null)) as pipeline_slippage,
max(case when section_name = '事件' and record not in('跌倒','摔伤','坠床','走失','自杀','管道滑脱') then record end) as other,
max(decode(section_name,'转归',record,null)) as result
from(
select nrft.id,nrf.ward_code,nrf.ward_name,nrf.bed_no,nrf.patient_id,nrf.pat_name,nrf.record_time,nr.item_id,nr.record,nrfs.section_name
from nursing_record_forms nrf,
nursing_record_form_templates nrft,
nursing_record_form_sections nrfs,
nursing_record_form_items nrfi,
nursing_records nr
where nrf.template_id = nrft.id
and nrfs.template_id = nrf.template_id
and nrfs.sequence in(1,6,4)
and nrfs.id = nrfi.section_id
and nr.form_id = nrf.id
and nr.section_id = nrfs.id
and nr.item_id = nrfi.item_id
and nrft.name in('走失危险因素评估报告表','跌倒/摔伤/坠床危险因素评估报告表','自杀危险因素评估报告表','病人管道滑脱评估报告表')
and nrf.record_time >= trunc(to_date(?,'yyyy-mm-dd hh24:mi:ss'),'year')
and nrf.record_time <= trunc(to_date(?,'yyyy-mm-dd hh24:mi:ss'),'year') - interval '1' second
) group by id,patient_id,record_time,ward_code)) where id is not null