Complex sql query requirement in db2 -


i have table follows:

   keycol     |     date_o_col      |    date_c_col   |    statcol --------------------------------------------------------------------       1            2007-02-09          2012-11-02          c       1            1990-01-31          <null>              o       1            <null>              <null>              o ------------------------------------------------------------------------    

i want write query following:

1) compares date values in both date columns find out max date between both of them. in example above 2012-11-02 max date in both columns.

2) since 2012-11-02 in date_c_col, resultant row of query should be:

   keycol     |     date_o_col      |    date_c_col   |    statcol --------------------------------------------------------------------       1             <null>               2012-11-02          c 

i.e. send max date in column in belonged corresponding statcol , send other date column null.

as other example, table status as:

       keycol  |     date_o_col      |    date_c_col   |    statcol --------------------------------------------------------------------       2            2016-02-09               2016-03-09        c       2            1990-01-31               2012-11-02        c       2            2016-03-10               <null>            o ------------------------------------------------------------------------  

should result in:

       keycol  |     date_o_col      |    date_c_col   |    statcol --------------------------------------------------------------------       2            2016-03-10               <null>            o 

since 2016-03-10 max date , belongs date_o_col corresonding statcol o.

i using db2 9.

you can use case:

select t.keycol,        (case when max(date_o_col) null , max(date_c_col) null null              when max(date_o_col) null 'c'              when max(date_c_col) null 'o'              when max(date_o_col) > max(date_c_col) 'o'              when max(date_c_col) > max(date_o_col) 'c'              else '='         end) t group keycol; 

i made values boundary cases question doesn't cover: when values both null or both equal.


Comments