Search code examples
t-sqlgroup-bysap-ase

Sybase ASE data grouping


I have the following data in Sybase ASE

   id   effectiveDate     lastModificationDate  rateValue    
 -----  ----------------  --------------------  ------------ 
 1      20130627          6/27/2013 3:27:09 AM  0            
 1      20130627          6/27/2013 4:39:10 AM  2.75         
 1      20130627          6/28/2013 3:48:15 AM  0            
 1      20130627          6/28/2013 4:36:43 AM  2.75         
 1      20130628          6/28/2013 3:48:14 AM  0            
 1      20130628          6/28/2013 4:36:42 AM  2.75         
 2      20130628          6/28/2013 4:36:42 AM  .75         
 2      20130628          6/28/2013 3:48:14 AM  0            

How do I group it, so that I get only the last row, ie I get the row which has the max lastModificationDate for the same id+effectiveDate.

So output would be :

 id     effectiveDate     lastModificationDate  value    
 -----  ----------------  --------------------  ------------ 
 1      20130627          6/28/2013 4:36:43 AM  2.75         
 1      20130628          6/28/2013 4:36:42 AM  2.75         
 2      20130628          6/28/2013 4:36:42 AM  .75         

Please note that this would be on TSQL (Sybase ASE 15). EDIT: Have changed the data to make it more realistic


Solution

  • Try:

    SELECT t1.*
    FROM Table1 t1
    WHERE t1.lastModificationDate  = (SELECT MAX(t2.lastModificationDate)
                                      FROM Table1 t2
                                      WHERE t2.effectiveDate = t1.effectiveDate
                                      AND t2.id = t1.id)
    

    Sybase documentation:

    Subqueries can be nested inside the where or having clause of an outer select, insert, update, or delete statement, inside another subquery, or in a select list. Alternatively, you can write many statements that contain subqueries as joins; Adaptive Server processes such statements as joins.