Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created January 27, 2016 12:37
Show Gist options
  • Save dnasca/0a92da041cf4fcfa3b33 to your computer and use it in GitHub Desktop.
Save dnasca/0a92da041cf4fcfa3b33 to your computer and use it in GitHub Desktop.
Common Table Expressions - multiple references to the same CTE
WITH
ProductQty (PID, LID, Shelf, Bin, Qty) AS
(SELECT
ProductId, LocationId, Shelf, Bin, Quantity
FROM
Production.ProductInventory)
SELECT
p1.PID,
SUM(p1.Qty) AS ShelfQty_A,
SUM(p2.Qty) AS ShelfQty_B
FROM
ProductQty AS p1
INNER JOIN
ProductQty AS p2
ON
p1.PID = p2.PID
WHERE
p1.Shelf = 'A' AND
p2.Shelf = 'B'
GROUP BY
p1.PID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment