You don't need to order by the column you are also partitioning. Also -- why select the rowNum column. I doubt you will use itSo your:select * from (select resellerkey,salesordernumber,OrderDateKey, SalesAmount, row_number() over (partition by resellerkey order by ResellerKey,OrderDateKey desc) as 'RowNum' from phsales ) as a where A.RowNum=1
Could become:SELECT resellerkey , salesordernumber , OrderDateKey , SalesAmountFROM ( SELECT resellerkey , salesordernumber , OrderDateKey , SalesAmount , ROW_NUMBER() OVER ( PARTITION BY resellerkey ORDER BY OrderDateKey DESC ) AS [rowNum] FROM phsales ) AS aWHERE a.RowNum = 1
Because you are ordering by only one column you may be able to turn this into a derived table using a GROUP BY and MAX (depending on whether the orderDateKey is guaranteed to be unique (which I'm guessing it is because the column has the word 'key' in it. I've found that a group by and MIN/MAX is slightly faster for me than the corresponding simple row_number solutionExample:SELECT phs.[resellerKey] , phs.[salesOrderNumber] , phs.[orderDateKey] , phs.[salesAmount]FROM ( SELECT [resellerKey] AS [resellerKey] , MAX([orderDateKey]) AS [maxOrderDateKey] FROM phsales GROUP BY [resellerKey] ) AS latestSales JOIN phSales AS phs ON phs.[resellerKey] = latestSales.[resellerKey] AND phs.[orderDateKey] = latestSales.[maxOrderDateKey]
Edit -- missed the DESCCharlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION