Skip to content

Instantly share code, notes, and snippets.

@carinavockell
Created September 12, 2022 16:31
Show Gist options
  • Save carinavockell/fa831c7a1706e10045064d8e8a9a5131 to your computer and use it in GitHub Desktop.
Save carinavockell/fa831c7a1706e10045064d8e8a9a5131 to your computer and use it in GitHub Desktop.
By using CROSS APPLY with a single subquery that returns the necessary columns, I can cut down the number of logical reads and the number of touches on the Sales.SalesOrderDetail table.
SELECT
SalesOrderDetailID,
UnitPrice,
CarrierTrackingNumber, x.*
FROM Sales.SalesOrderDetail o
CROSS APPLY
(
SELECT
RunningTotal = SUM (UnitPrice),
RowCnt = COUNT (*)
FROM Sales.SalesOrderDetail i
WHERE i.CarrierTrackingNumber = o.CarrierTrackingNumber
AND i.SalesOrderDetailID <= o.SalesOrderDetailID
) x
WHERE o.CarrierTrackingNumber IS NOT NULL
ORDER BY CarrierTrackingNumber ASC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment