If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > How to pull the most recent order for each customer?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-28-11, 02:07
wungexh wungexh is offline
Registered User
 
Join Date: Nov 2011
Posts: 19
How to pull the most recent order for each customer?

I have a db that is full of orders, along with the customers name, address, etc. There are multiple entries for each customer because they have purchased things more than once. I need to export a table that has all the customers and only their most recent order. I figure I can use the `id` field because they are unique and the highest `id` means the most recent.

I just need to filter out the most recently entered `id` along with the rest of the info in the fields all the way down the row for each customer.

The table is named orders and the id is just called `id`

Any ideas??
Reply With Quote
  #2 (permalink)  
Old 11-28-11, 02:40
it-iss.com it-iss.com is offline
Registered User
 
Join Date: Sep 2009
Location: San Sebastian, Spain
Posts: 620
You need to make sure that your 'id' field is incremental and that the max per customer is indeed correct. Also how do you define a customer by its name and/or address? For example, a name may not be unique enough so you may also need to link in the address. However, differences in spelling of the address may cause issues with your results.

Try the following (if name and address uniquely defines each customer):

SELECT customerName, address, max(id)
FROM orders
GROUP BY customerName, address;
__________________
Ronan Cashell
Senior Oracle/MySQL DBA
http://www.it-iss.com
Reply With Quote
  #3 (permalink)  
Old 11-28-11, 04:50
healdem healdem is online now
Jaded Developer
 
Join Date: Nov 2004
Location: out on a limb
Posts: 9,250
the highest id field may effectively mean its the most recent, but you should not rely on an autogenerated column as having any other meaning that a means to make a row unique. what you should be doing is using a date time column when the order was placed.
__________________
I'd rather be riding my Versys or my Tiger 800 let alone the Norton
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On