Skip to content

Instantly share code, notes, and snippets.

@carinavockell
Created September 12, 2022 16:19
Show Gist options
  • Save carinavockell/46e2f1f8aa9f9e1690c370e116393b89 to your computer and use it in GitHub Desktop.
Save carinavockell/46e2f1f8aa9f9e1690c370e116393b89 to your computer and use it in GitHub Desktop.
This results in a much more efficient execution plan because the optimizer can use a MERGE JOIN rather than being forced to use an INNER JOIN as with the CROSS APPLY query above.
SELECT
soh.SalesOrderID,
soh.OrderDate,
sub.*
FROM Sales.SalesOrderHeader soh
JOIN
(
SELECT
sod.SalesOrderID,
SUM (sod.UnitPrice) AS UnitPrice,
SUM (sod.OrderQty) AS Quantity
FROM Sales.SalesOrderDetail sod
GROUP BY sod.SalesOrderID
) sub
ON sub.SalesOrderID = soh.SalesOrderID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment