Skip to content

Instantly share code, notes, and snippets.

@gbdavid2
Last active February 19, 2017 20:27
Show Gist options
  • Save gbdavid2/068e67b711b5f0f72670 to your computer and use it in GitHub Desktop.
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
--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