Common Table Expression (CTE) Use Cases
Contents
CTEs can …
- aid readability of a query
- be used as an alternative to derived tables (aka nested subqueries)
- be referenced multiple times
- be used for recursive queries
Here are some use cases.
Filtering or Grouping on Windowing Function
Here are the top two cities by population for each state in the table.
|
|
Nested Aggregate Functions
Here it’s using the same numbers as Population above but let’s call it TotalSales for this example, and we will calculate the average sales for a state.
|
|
Recursive Queries
Here we have one of the classic recursive examples, a list of employees and their managers.
|
|