Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retrieving latest entry for each set of two or more repeating keys

T-SQL Hints and Tips

Retrieving latest entry for each set of two or more repeating keys

by  shnaeem  Posted    (Edited  )
You could more easily understand the scenerio with a simple example. Consider a table containing orders given by different customer for different products
Orders (Order_ID, Product_id, Cust_id, Orderdate, Description)
Customer_id and product_id are set of repeating values. They could have number of occurance with different dates of course.
Now you have to retrieve the latest order given by each customer for each product. One way is to write this query

Select max(order_date), cust_id, product_id
from orders
group by cust_id, product_id


and then place a join with the same table to retrieve the Order_id (As it is not in aggregation function)

There is another way around.
Use this query instead

Select max(Order_id), max(order_date), cust_id, product_id
from orders
group by cust_id, product_id


Isn't this great
and to increase the speed of the query use indexing. It really fly that way. Experience...... [img http://www.tipmaster.com/images/smiletiniest.gif]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top