Layered CTE Pipeline
Compose a multi-stage query as named CTE layers — filter, deduplicate, then aggregate — so each stage reads independently and later stages stay simple.
Code
-- 多层 CTE 管线:每层解决一件事,后层只依赖前层的名字
WITH incidents (host, severity, opened_at) AS (
VALUES
('web-1', 'high', 1),
('web-1', 'low', 2),
('web-1', 'high', 3),
('db-1', 'medium', 4),
('db-1', 'high', 5)
),
-- 第 1 层:过滤出需要处理的行(pipeline 的入口)
urgent AS (
SELECT host, severity, opened_at
FROM incidents
WHERE severity IN ('high', 'medium')
),
-- 第 2 层:同主机只保留最早一条(去重语义集中在这一层)
first_per_host AS (
SELECT DISTINCT ON (host) host, severity, opened_at
FROM urgent
ORDER BY host, opened_at
)
-- 第 3 层:汇总层只写聚合,不再操心过滤与去重
SELECT count(*) AS hosts_with_first_urgent,
count(*) FILTER (WHERE severity = 'high') AS starting_high
FROM first_per_host;Inside the snippet
At its core this is a single SELECT statement against incidents, urgent and first_per_host.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause filtering the rows one statement applies to; COUNT aggregation; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.
Putting it to use
The incidents 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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- The references are `incidents`, `urgent`, `first_per_host`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.