CTE Column List Aliases Computed Columns

Name computed CTE columns explicitly with a column list so two aggregates stop sharing the generated name sum and downstream CTEs join unambiguously.

SqlData Fetching

Code

snippet
-- the column list aliases computed columns instead of engine-generated names
WITH totals(day, orders, revenue) AS (
    SELECT
        created::date,
        count(*),
        sum(amount)
    FROM orders
    GROUP BY created::date
),
-- 下游 CTE 按命名后的列引用,两个 sum 不再撞名
big_days AS (
    SELECT day, revenue
    FROM totals
    WHERE revenue > 1000
)
SELECT t.day, t.orders, t.revenue, b.day AS big_day
FROM totals t
JOIN big_days b USING (day);

How the snippet works

At its core this is a single SELECT statement against orders, totals and big_days.

In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group.

Applying it

The orders table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`orders`, `totals`, `big_days` — joined via one JOIN clause.