Comment on page
Lesson 20. Common Table Expressions (CTEs)
CTEs are virtual datasets that you can create. When you create your CTE, it can be treated just like a table.
The use case for CTEs is when you want to encapsulate business logic. Sometimes queries get too hairy and it is easier to just separate the datasets so the query is easier to write.
The name of the columns that define the output of your CTE do not have to match the columns of the SQL statement used to create the CTE. Sometimes it is nice that they are the same. Other times, it is nice to have them different, especially if you are running a calculation on a particular column that winds up redefining the column definition. A good example would be running SUM() on DollarAmount. That column now represents total dollar amount and now the original column name is not very informative.
WITH CTEName(Column1, Column2,...ColumnN)
--SQL statement that encapsulates complex business logic
--The main SQL statement that joins on the CTE
Basic CTE Example
WITH PersonWithNoMiddleName(BusinessEntityID, FirstName, LastName)
SELECT BusinessEntityID, FirstName, LastName
WHERE MiddleName IS NULL
FROM Person.EmailAddress e
JOIN PersonWithNoMiddleName pwnmn
ON pwnmn.BusinessEntityID = e.BusinessEntityID