Pivot Rows to Columns CASE Aggregation
Pivot monthly revenue by category using conditional aggregation, generating column lists dynamically for any date range.
Code
-- 固定月份的手写透视:CASE 进聚合函数
SELECT
category,
SUM(amount) FILTER (WHERE month = '2026-07') AS jul_revenue,
SUM(amount) FILTER (WHERE month = '2026-08') AS aug_revenue,
SUM(amount) FILTER (WHERE month = '2026-09') AS sep_revenue,
SUM(amount) AS total_revenue
FROM monthly_revenue
GROUP BY category
ORDER BY total_revenue DESC;
-- 经典写法对照:CASE WHEN 的条件聚合
SELECT
category,
SUM(CASE WHEN month = '2026-07' THEN amount ELSE 0 END) AS jul_revenue,
SUM(CASE WHEN month = '2026-08' THEN amount ELSE 0 END) AS aug_revenue
FROM monthly_revenue
GROUP BY category;
-- 生成动态列清单(应用层据此拼 SQL)
SELECT DISTINCT month
FROM monthly_revenue
WHERE month BETWEEN '2026-07' AND '2026-09'
ORDER BY month;What the code does
Several statements share this file — SELECT, with monthly_revenue among the objects involved.
The pieces that do the work: a WHERE clause narrowing which rows one statement affects; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.
Applying it
The monthly_revenue table is the working surface here.
Statements that matter
SELECT
category,
SUM(amount) FILTER (WHERE month = '2026-07') AS jul_revenue,
SUM(amount) FILTER (WHERE month = '2026-08') AS aug_revenue,
SUM(amount) FILTER (WHERE month = '2026-09') AS sep_revenue,
SUM(amount) AS total_revenue
FROM monthly_revenue
GROUP BY category
ORDER BY total_revenue DESC;
SELECT
category,
SUM(CASE WHEN month = '2026-07' THEN amount ELSE 0 END) AS jul_revenue,
SUM(CASE WHEN month = '2026-08' THEN amount ELSE 0 END) AS aug_revenue
FROM monthly_revenue
GROUP BY category;
SELECT DISTINCT month
FROM monthly_revenue
WHERE month BETWEEN '2026-07' AND '2026-09'
ORDER BY month;
Interactive Tools for This Topic
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.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.Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.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
- Name the tables involved in this file.
- `monthly_revenue` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.