Grab the first rows and put it to column wise

Advertisement
Below are two dump, i want to grab the first 2 rows in ascending order by from_date and put to column wise, the first row label first_charge and second row as second_charge. AND throw away rows from 3 are not needed.
1st dump 5 columns are my input,
2nd dump 3 columnS ARE my desired output.
I have tried the rank function but can someone please confirm this is correct way to do this for all the accounts in the table
Script (table and data) for 1st dump is at bottom of post.
Can anyone help resolve this issue - thanks.
--FIRST DUMP
ACCOUNT_ID     CHARGE_AMT     CHARGE_DATE     FROM_DATE     THRU_DATE
212855740     14.52          5/04/2012     14/03/2012     31/03/2012
212855740     25          5/04/2012     1/04/2012     30/04/2012
212855740     25          5/05/2012     1/05/2012     31/05/2012
212855740     25          5/06/2012     1/06/2012     30/06/2012
212855740     25          5/07/2012     1/07/2012     31/07/2012
212855740     25          5/08/2012     1/08/2012     31/08/2012
212855740     25          5/09/2012     1/09/2012     30/09/2012
212855740     25          5/10/2012     1/10/2012     31/10/2012
212855740     25          5/11/2012     1/11/2012     30/11/2012
--DESIRED DUMP                    
ACCOUNT_ID     PRO_CHARGE     MONTHLY_CHARGE          
212855740     14.52          25          
WITH CHARGE_TABLE_QUERY
     AS (SELECT account_id,
                charge_amt,
                charge_date,
                from_date,
                thru_date,
                ROW_NUMBER ()
                   OVER (PARTITION BY account_id ORDER BY from_Date)
                   row_num
           FROM my_tbl)
  SELECT account_id,
         MAX (CASE WHEN ROW_NUM = 1 THEN CHARGE_AMT ELSE 0 END) PRO_CHARGE,
         MAX (CASE WHEN ROW_NUM = 2 THEN CHARGE_AMT ELSE 0 END) MONTHLY_CHARGE
    FROM CHARGE_TABLE_QUERY q
   WHERE row_num IN (1, 2)
GROUP BY account_id;
Advertisement

Replay

ricard888 wrote:
what happens if a new account where there is no second charge yet. can i have either null or 0 in the monthly_charge.You could test it easily. Anyhow, it will work without any change in the code
insert into my_table
select 1,50,CHARGE_DATE,FROM_DATE,THRU_DATE
from my_table
where rownum = 1;
1 rows inserted.
with CHARGE_TABLE_QUERY as
  select account_id,charge_amt,
         ROW_NUMBER ()
            OVER (PARTITION BY account_id ORDER BY from_Date)  rn,
         lead(charge_amt)
           OVER (PARTITION BY account_id ORDER BY from_Date) MONTHLY_CHARGE
  from my_table
select account_id,charge_amt pro_charge,monthly_charge
from CHARGE_TABLE_QUERY
where rn = 1;
ACCOUNT_ID PRO_CHARGE MONTHLY_CHARGE
         1         50               
212855740      14.52             25