O'Reilly logo

Inside Microsoft® SQL Server™ 2005: T-SQL Querying by Dejan Sarka, Lubor Kollar, Itzik Ben-Gan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Solutions to Common Problems Using TOP and APPLY

Now that the fundamentals of TOP and APPLY have been covered, I’ll present common problems and solutions that use TOP and APPLY.

TOP n for Each Group

In Chapter 4 and Chapter 6, I discussed a problem involving tiebreakers where you were asked to return the most recent order for each employee. This problem is actually a special case of a more generic problem where you are after the top n rows for each group—for example, returning the three most recent orders for each employee. Again, orders with higher OrderDate values have precedence, but you need to introduce a tiebreaker to determine precedence in case of ties. Here I’ll use the maximum OrderID as the tiebreaker. I’ll present solutions to this class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required