Original Post
I believe I've bitched about it before, but I don't think I can go much longer having to create a situation specific solution (that comes way too close to having holes and problems if the right is used) everytime I come up against this problem. For reference this is under SQL Server 2000. The problem is simple. You want to list the TOP 1 item from a list based on a specified sorting order. However you don't just want one item, you want to take a table/view and find the first item in the sorting order for each item in a group. Lets take a hypothetical example. We have a table for employees: CREATE TABLE Employees(Name varchar(100), Age integer, Salary integer, DepartmentID integer); As you can see, for each employee we know their age and their department and how much they make. What we want to do is find the oldest employee in each department, how old they are, and how much they make. If there is a tie, then we want to break it by the order of their name. For example to find the oldest in one department the query would look like this: SELECT * FROM Employees WHERE DepartmentID=# ORDER BY Age DESC, Name However we don't want one department at a time. We want to be able to list the oldest employee in each department in one query. Something along the lines of this (note, the FIRST aggregate function only exists in JET, and you can't make user defined aggregate functions unless you go to something like SQL Server 2005 or Oracle 9. Even in JET I'm not sure if this is valid or not as I'm not a pro-Access programmer). SELECT FIRST(Name), FIRST(age), FIRST(Salary), DepartmentID FROM Employees GROUP BY DepartmentID ORDER BY Age DESC, Name There is a big rate up if anyone can find a general purpose, robust solution to this problem. I'm also rating up to anyone with insightful comments or sucking up.