Solved

Last 2 orders by customer

Posted on 2016-09-12
2
36 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
Comment Utility
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
Comment Utility
Perfect
Thanks
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Join & Write a Comment

Suggested Solutions

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

763 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now