Solved

Last 2 orders by customer

Posted on 2016-09-12
2
61 Views
Last Modified: 2016-09-12
I need to select the last 2 orders and dates by customer from a sales order table.

The table would have the customer number, docdate, order amount, order number etc..

Not quite sure the easiest way to do that.

Thanks
0
Comment
Question by:jdr0606
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 41794159
Couple of different ways to do this, but simplest is to use the RANK() keyword to rank all orders for each customer by the order date, then pick the top two.

Table and column names are samples, change these names to fit your situation.
SELECT CustomerID, OrderID, RankOrder
FROM (
   SELECT CustomerID, OrderID, 
     RANK() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC) as RankOrder
   FROM SalesOrderTable) a
WHERE RankOrder <= 2

Open in new window

0
 

Author Closing Comment

by:jdr0606
ID: 41794535
Perfect
Thanks
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how to solve "recursive" database tables 2 59
sql server connection string in config file 4 41
Datatable / Dates ? 4 33
relocating SQL 2000 18 39
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question