CTE Feeds The Review Workflow

Chain two CTEs so one statement ranks submitted items and joins reviewer assignments, producing the review queue in a single snapshot.

SqlData Integrity

Code

snippet
WITH submitted AS (
    -- 第一步:过滤与打分,只留待审条目
    SELECT
        s.item_id,
        s.title,
        s.submitted_at,
        -- 风险分:越新越大,同分按提交时间定序
        round(EXTRACT(EPOCH FROM (now() - s.submitted_at)) / 3600.0, 1)
            AS hours_waiting,
        CASE s.risk_tag WHEN 'high' THEN 100
                        WHEN 'medium' THEN 40
                        ELSE 10 END AS risk_points
    FROM submissions s
    WHERE s.status = 'submitted'
),
queue AS (
    -- 第二步:按风险加等待时长排优先级
    SELECT
        item_id,
        title,
        submitted_at,
        hours_waiting,
        risk_points + hours_waiting AS priority,
        ROW_NUMBER() OVER (ORDER BY risk_points + hours_waiting DESC)
            AS queue_position
    FROM submitted
)
SELECT
    q.queue_position,
    q.title,
    round(q.priority::numeric, 1) AS priority,
    a.reviewer_id
FROM queue q
LEFT JOIN reviewer_assignments a
       ON a.item_id = q.item_id
-- 还没有指派审核人的排最前:LEFT JOIN 保留 NULL 侧
ORDER BY (a.reviewer_id IS NULL) DESC, q.queue_position
LIMIT 20;

How it works

What runs is SELECT, with submissions, submitted, queue and reviewer_assignments as the object involved.

Breaking the statements into their working parts: 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; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

Run the statement against the submissions table; the LIMIT keeps the probe cheap while you tune the predicates.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`submissions`, `submitted`, `queue`, `reviewer_assignments` — joined via one JOIN clause.