Last active
February 19, 2017 20:27
-
-
Save gbdavid2/068e67b711b5f0f72670 to your computer and use it in GitHub Desktop.
AdventureWorks: Double CTE solution to retrieving data about latest orders by customer name and date, filtered by sales person 289
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--SP | |
DECLARE @SalesPersonID INTEGER | |
DECLARE @ProvidedTop INTEGER | |
SET @SalesPersonID = 289 | |
SET @ProvidedTop = 10; | |
--- All the orders that were created for the Customers | |
WITH CTE_OrderDates | |
AS | |
( | |
SELECT P.FirstName +' '+P.LastName As ClientName, | |
SOH.OrderDate, RANK() OVER ( PARTITION BY P.FirstName +' '+P.LastName, SOH.OrderDate | |
ORDER BY SOH.OrderDate,P.FirstName +' '+P.LastName DESC) AS RowNumber | |
FROM Sales.SalesOrderHeader SOH | |
JOIN Sales.Customer C ON SOH.CustomerID = C.CustomerID | |
JOIN Person.Person P ON P.BusinessEntityID = C.PersonID | |
WHERE SalesPersonID = @SalesPersonID -- Modified by the Specific Person | |
), | |
CTE_CustomerDates | |
AS | |
( | |
SELECT C.*, ROW_NUMBER() OVER ( ORDER BY C.OrderDate DESC) PriorityRow FROM CTE_OrderDates C | |
WHERE RowNumber = 1 | |
) | |
SELECT * FROM CTE_CustomerDates WHERE PriorityRow <= @ProvidedTop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment