Beginner

670. JOIN with Multiple CTEs

Combine multiple Common Table Expressions to build a structured analytical JOIN query.

📘 Lesson 670 of 728 ⏱ 16 min 🎯 Advanced

Multiple CTEs allow complex logic to be divided into separate named result sets that can later be JOINed together.

Breaking a complex query into logical stages makes calculations easier to understand, test, and maintain.

Create separate customer sales and support-ticket summaries and combine them into one customer report.

SQL
WITH SalesSummary AS (
    SELECT
        CustomerID,
        SUM(OrderAmount) AS TotalSales
    FROM Orders
    GROUP BY CustomerID
),
TicketSummary AS (
    SELECT
        CustomerID,
        COUNT(TicketID) AS TicketCount
    FROM SupportTickets
    GROUP BY CustomerID
)
SELECT
    c.CustomerName,
    COALESCE(s.TotalSales, 0) AS TotalSales,
    COALESCE(t.TicketCount, 0) AS TicketCount
FROM Customers c
LEFT JOIN SalesSummary s
    ON c.CustomerID = s.CustomerID
LEFT JOIN TicketSummary t
    ON c.CustomerID = t.CustomerID;

Used in management reporting, customer analytics, financial MIS, and complex data pipelines.

  • Multiple CTEs can separate business logic.
  • Each CTE can operate at a controlled grain.
  • CTEs can then be JOINed in the final query.
  • Pre-aggregation helps avoid row multiplication.
  • COALESCE can handle missing summary records.
Can a query contain multiple CTEs?

Yes. Multiple CTEs can be defined in one WITH clause and used by the final query.

Why use multiple CTEs in reporting?

They separate independent calculations into manageable steps and make complex JOIN logic easier to maintain.

Have you finished this lesson?

Introduction to SQL – All Lessons