Search code examples
sqljoincursordb2

Using cursor for fetching multiple rows and setting its data in columns


My scenario is I have to populate data into a table by performing join on two tables A and B on the basis of column quoteid and compid

 Table A                                        
 ------------------------------  
 quoteid    compid ................
 10004        1
 10004        1
 10004        1
 10004        22
 10004        22
 10004        22 

 Table B
 ------------------------------------ 
 quoteid    compid   quartercode    cost
 10004        1          1q10        14
 10004        1          2q09        10 
 10004        1          3q10        12  
 10004        22         4q12        32 
 10004        22         3q11        30 
 10004        22         2q11        43

Now, the result of select query should be like

 quoteid compid quarter1cost  quarter2cost quarter3cost 
 10004     1         10           14           12
 10004     22        43           30           32

The concept to select cost for quarter is with quartercode which is combination of quarter in year(1st,2nd...) and last two digits of year. So, oldest quarter will with quarter1 , second oldest will be quarter2 and most recent will be quarter3. Here, there cost will be available for only 3 recent quarters due to join conditions. For example, here for quoteid 10004 and compid 1, quarter1 will be 2q09, quarter2 will be 1q10 and quarter3 will be 3q10 and hence the cost.

I am trying to do it with cursor. But since I am new so unable to get the desired result.


Solution

  • Table A seems to have nothing to do with your result.

    The basic idea is to use row_number() and conditional aggregation. This is complicated because you the quarter identifier is stored backwards, so it doesn't sort correctly. But you can still do it:

    select quoteid, compid,
           max(case when seqnum = 1 then cost end) as cost_q1,
           max(case when seqnum = 2 then cost end) as cost_q2,
           max(case when seqnum = 3 then cost end) as cost_q3
    from (select b.*,
                 row_number() over (partition by quoteid, compid
                                    order by substr(quartercode, 1, 1), substr(quartercode, 3, 2)
                                   ) as seqnum
          from b
         ) b
    group by quoteid, compid