mssql window function query, get last order from group
- User
mssql window function query, get last order from group
- Assistant
To retrieve the last order from each group using a SQL Server (MSSQL) window function, you can use the
ROW_NUMBER()function. This function can help you assign a unique sequential integer to rows within a partition of a result set, ordered by a specified column.Here's a general example that demonstrates this concept:
Sample Table Structure
Assuming we have an
Orderstable structured like this:sqlCREATE TABLE Orders ( OrderID INT, CustomerID INT, OrderDate DATETIME, Amount DECIMAL(10, 2) );Query to Get Last Order from Each Customer
You want to get the most recent order for each customer based on the
OrderDate. Here's how you can do that:sqlWITH RankedOrders AS ( SELECT OrderID, CustomerID, OrderDate, Amount, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate DESC) AS rn FROM Orders ) SELECT OrderID, CustomerID, OrderDate, Amount FROM RankedOrders WHERE rn = 1;Explanation
-
Common Table Expression (CTE):
- The query uses a CTE named
RankedOrdersto first rank the orders for each customer.
- The query uses a CTE named
-
ROW_NUMBER()Function:ROW_NUMBER()is used to assign a unique number (rn) to each order for a customer, ordered byOrderDatein descending order (most recent first).- The
PARTITION BY CustomerIDclause ensures that the row numbering restarts for each customer.
-
Filtering:
- The outer query selects the details from the CTE where
rn = 1, which gives us the most recent order for each customer.
- The outer query selects the details from the CTE where
Alternative: Using
RANK()orDENSE_RANK()If you might have ties in order dates and want to include all last orders for those tied dates, consider using
RANK()orDENSE_RANK()instead of : -