Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Common Table Expressions Using WITH!

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
Learn how to use multiple common table expressions within a query, and even how to reference one CTE within another CTE to create more complex reports with aggregate data.
Example Code
CTEs Referencing a CTE
WITH
all_sales AS (
SELECT Orders.Id AS OrderId, Orders.EmployeeId,
SUM(OrderDetails.UnitPrice * OrderDetails.Quantity) AS invoice_total
FROM Orders
JOIN OrderDetails ON Orders.id = OrderDetails.OrderId
GROUP BY Orders.ID
),
revenue_by_employee AS (
SELECT EmployeeId, SUM(invoice_total) AS total_revenue
FROM all_sales
GROUP BY EmployeeID
),
sales_by_employee AS (
SELECT EmployeeId, COUNT(*) AS sales_count
FROM all_sales
GROUP BY EmployeeId
)
SELECT
Employees.Id,
Employees.LastName,
revenue_by_employee.total_revenue,
sales_by_employee.sales_count,
revenue_by_employee.total_revenue/sales_by_employee.sales_count AS
avg_revenue_per_sale
FROM revenue_by_employee
JOIN sales_by_employee ON revenue_by_employee.EmployeeId = sales_by_employee.EmployeeId
JOIN Employees ON revenue_by_employee.EmployeeId = Employees.Id
ORDER BY total_revenue DESC
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up-
RYAN Anthony HARRIS
6,498 Points4 Answers
-
Ahmed Mohamed Fouad
11,735 Points1 Answer
-
izzy goldman
12,542 Points1 Answer
View all discussions for this video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up