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.

SqlData Fetching

Code

snippet
-- 多层 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

FAQ

Which tables does this file reference?
The references are `incidents`, `urgent`, `first_per_host`.