cope
cope

Reputation: 95

SQL aggregation

The following is T-SQL executed through a Business Objects package. My question is, is there a shorter way of completing the following aggregation for a query:

(SELECT tblName.Details
 FROM   tblName
 WHERE  tblName.ID = (SELECT Max(tblName2.ID)
                      FROM   tblName tblName2
                      WHERE  tblMainQuery.id = tblName2.id
                             AND tblName2.StartDate = (SELECT Max(tblName3.StartDate)
                                                       FROM   tblName tblName3
                                                       WHERE  tblMainQuery.id = tblName3.id))) 

tblMainQuery.id is a field which makes it a correlated sub-query.

So to summarise, I want to implement this whole query as a sub-query, in which I want to retrieve the id of the most recent start date, but as the most recent start date might return more than one record, go down to primary key level and retrieve the highest primary key.

I know using a CTE would help but this isn't possible as it must be executed through Business Objects Web Intelligence - this isn't supported.

Upvotes: 0

Views: 141

Answers (2)

Pரதீப்
Pரதீப்

Reputation: 93694

Try this

SELECT *
FROM   tblName A
       JOIN (SELECT TOP 1 Row_number()
                            OVER (
                              ORDER BY startdate, id) row_n,
                          *
             FROM   tblName
             ORDER  BY row_n DESC) B
         ON A.id = b.id 

Upvotes: 0

HoneyBadger
HoneyBadger

Reputation: 15140

I would probably try a ROW_NUMBER. Order by startDate to get the max startDate, further order by ID to get the max ID belonging to the max StartDate. Then select only records with ROW_NUMBER = 1.

Upvotes: 1

Related Questions