Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL
Expertise: Intermediate
Aug 11, 2009

Avoid Multiple Queries When Querying for Max and Min Values

Often, when you need to get the maximum or minimum value for a specific column, you are also interested in getting more data about those particular rows, so you end up writing two queries. That's not bad when the queries are simple, but if you have a long-running query that joins several tables and perhaps even performs some complicated calculations, you will have to double the size and complexity of the query just to get more data.

Instead, you can use the RANK() and DENSE_RANK() functions in T-SQL to get the additional data using a single query. For example, suppose you want to get the orders with the highest total for each customer. You can do it like this:

SELECT *
FROM
(
    SELECT C.CustomerId, O.OrderId, O.OrderDate,
        C.FIRSTNAME, C.LASTNAME, SUM(D.Quantity * P.Price) AS Total,
        RANK() OVER (PARTITION BY C.CustomerId ORDER BY SUM(D.Quantity * P.Price) DESC) AS [RANK]
    FROM [Order] O
    INNER JOIN OrderDetail D ON O.OrderId = D.OrderId
    INNER JOIN Product P ON D.ProductId = P.ProductId
    INNER JOIN Customer C ON O.CustomerId = C.CustomerId
    GROUP BY O.OrderId, O.OrderDate, C.CustomerId,
        C.FIRSTNAME, C.LASTNAME
) A
WHERE [RANK] = 1

This example uses the RANK function to get the order number for each row of the final total table (total calculated by summing up the price of each item times its quantity in the order) when in descending order. The PARTITION keyword groups the results by CustomerID before ordering the results. So the final result is that the query returns the rows where the rank is 1—which are the orders with the highest total for each customer.

Cindy Rodriguez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap