Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Joe writes "I have a table that holds the history of purchases and I need to select the latest 2 orders from each customer, the table looks something like this:Customer ID Item Cost Buy Date Buy Time1 item1 10 20040708 12342 item2 15 20040707 245011 item2 12 20040702 351023 item3 10 20040702 12541 1 item1 9 20040615 2154The key for this table is the customer id, buy date and buy time, it is a VERY large data base so efficiency is a big issue as well. Thanks for your help in advance, this web site has been a HUGE help to me so far."
spirit1
Cybernetic Yak Master
11752 Posts
Posted - 2004-09-07 : 09:22:24
this should help:
SELECT CustomerID, Item, Cost, BuyDate, BuyTimeFrom MyTable t1WHERE BuyDate IN (SELECT TOP 2 BuyDate FROM MyTable WHERE CustomerId = t1.CustomerId ORDER BY BuyDate DESC)ORDER BY CustomerId, BuyDate DESC