简体   繁体   中英

How to retrieve data from previous record from maximum in ORACLE DB

I have a table with Client Name , Contract_id , and four columns Total1 , Total2 , Total3 and Total4 .

I need to retrieve in one row for each client the values of Total1 , Total2 , Total3 and Total4 from maximum record and previous record.

Have next:

enter image description here

在此处输入图像描述

Need to get like that:

在此处输入图像描述

Thank you!

You can use something like the below which comes close to your requirement. The DB Fiddle here

with data as (select t.*,Row_number() over(partition by c_name order by rownum) row_num from testtt1 t 

    ),data1 as (
    select c_name,LISTAGG((c_id || ',' || t1 ||','|| t2 || ',' || t3 ||',' ||t4), '| ') WITHIN GROUP (ORDER BY row_num)  product_info from data
    where row_num<=2
    group by c_name
    union 
    select 'c_name' c_name,LISTAGG(('c_id' || ',' || 't1' ||','|| 't2' || ',' || 't3' ||',' ||'t4'), '| ') WITHIN GROUP (ORDER BY row_num)  product_info from data
    where row_num<=1
    group by 'c_name'
    )
    select c_name as " ",replace(product_info,',',chr(9)) as " " from data1
    order by decode(c_name,'c_name',c_name) ;

The Answer looks like the below

        c_name  c_id    t1  t2  t3  t4| c_id    t1  t2  t3  t4
        Company 583002  100 200 300 400| 564015 100 800 500 400
        Ontario 550705  100 200 300 400| 552854 100 800 500 400

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM