One problem I haven’t been able to solve in a satisfying way is to create a query that returns a full row based on an aggregate function. Suppose we have the following database schema: If you need to write a query that returns the most expensive book for each customer you probably would first write a query like:

Which results in this error:

Column ‘Books.Price’ is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

The only solution I found was to create a sub-query that returns price of the most expensive book per customer and join that sub query on the price. Since Sql server 2008 there is a very nice solution to this problem. The ROW_NUMBER PARTITION function, that function returns a row number for each record, which in nice. But how is this going to solve your problem? That will happen when you use the “OVER (PARTITION BY …. ORDER BY…) “. This tells Sql server when the row number needs to be reset and how to number. For our database schema this this query looks like this:

This query returns all books every customer has ordered, with an extra column “rownumber” that is reset per customer, and is ordered from highest to lowest price: Now, all we need to do is to get the rows where rownumber equals 1. For that we need to create a sub query, but this sub queru doesn’t cause any extra table scans and is very light:

That gives use this result: And that is what e needed in the first place.
[null, {"document_url": "http://coding.feron.it/2012/08/mssql-having-maxid-id-problem-row_number-partition/", "unformatted_src": "http://www.feron.it/images/DatabaseDiagram.png", "src": "http://www.feron.it/images/DatabaseDiagram.png", "formatted_filename": "DatabaseDiagram"}, null, {"document_url": "http://coding.feron.it/2012/08/mssql-having-maxid-id-problem-row_number-partition/", "unformatted_src": "http://www.feron.it/images/QueryResult.png", "src": "http://www.feron.it/images/QueryResult.png", "formatted_filename": "QueryResult"}, null, {"document_url": "http://coding.feron.it/2012/08/mssql-having-maxid-id-problem-row_number-partition/", "unformatted_src": "http://www.feron.it/images/QueryResult2.png", "src": "http://www.feron.it/images/QueryResult2.png", "formatted_filename": "QueryResult"}, null, null]