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!
You have completed Common Table Expressions Using WITH!
Preview
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 upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
CTEs also help organize our queries to
match how we think about a data question.
0:00
They're also really helpful when you want
to analyze data from a single result set
0:01
in different ways to create a new result
set that summarizes aggregate data.
0:04
Let's look at a simple example.
0:09
Say I want to see a list of sales people,
the total number of sales for
0:12
each employee, the total revenue
generated by each employee,
0:15
as well as the average
revenue generated per sale.
0:19
Data like this is stored in a database
that includes several tables.
0:22
In this basic example,
I only need to think about three tables.
0:26
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