Mark As Completed Discussion

CTE Example

Let us now better understand the concept of CTEs by taking a look at how to create one. First of all, we should have a table that we’ll be working with; in our example, that would be the following table (named Table1):

CTE Example
Imagine we’d like to get the same table as above, but with one extra row – the Average age of all people that ordered the same number of items that year. In order to do this, we can use a Common Table Expression, as shown below:

TEXT/X-SQL
1WITH Avg_age AS (
2  SELECT
3    EXTRACT(year FROM DateOfOrder) AS year,
4    NumberOfItems,
5    AVG(Age) AS AverageAge
6  FROM Table1
7  GROUP BY EXTRACT(year FROM DateOfOrder) , NumberOfItems
8)
9SELECT
10  Table1.*,
11  avg.Avg_age
12FROM Table1
13JOIN Avg_age avg	
14  ON EXTRACT(year FROM Table1.DateOfOrder) = avg.year
15    AND Table1.NumberOfItems = avg.NumberOfItems

The resulting table, after the execution of this query, would look like this:

CTE Example