Solved

Last 2 orders by customer

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

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

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

In this article I will describe the Backup & Restore 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.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

773 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