Solved

Last 2 orders by customer

Posted on 2016-09-12
2
65 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 66

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

Independent Software Vendors: 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

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

617 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