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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables or CTEs does it reference?
- `orders`, `totals`, `big_days` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.