-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommon_table_expression.sql
More file actions
41 lines (31 loc) · 871 Bytes
/
Copy pathcommon_table_expression.sql
File metadata and controls
41 lines (31 loc) · 871 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
-- Using a CTE
WITH ProductsByCategory (ProductID, ProductName, Category)
AS
(
SELECT p.ProductID, p.Name, c.Name AS Category
FROM SalesLT.Product AS p
JOIN SalesLT.ProductCategory AS c
ON p.ProductCategoryID = c.ProductCategoryID
)
SELECT Category, COUNT(ProductID) AS Products
FROM ProductsByCategory
GROUP BY Category
ORDER BY Category;
-- Recursive CTE
SELECT * FROM SalesLT.Employee2
-- Using the CTE to perform a recursive operation
WITH OrgReport (ManagerID, EmployeeID, EmployeeName, Level)
AS
(
-- Anchor query
SELECT e.ManagerID, e.EmployeeID, EmployeeName, 0
FROM SalesLT.Employee2 AS e
WHERE ManagerID IS NULL
UNION ALL
-- Recursive query
SELECT e.ManagerID, e.EmployeeID, e.EmployeeName, e.Level + 1
FROM SalesLT.Employee2 AS e
INNER JOIN OrgReport AS o ON e.ManagerID = o.EmployeeID
)
SELECT * FROM OrgReport
OPTION (MAXRECURSION 3);