Pivot Rows to Columns CASE Aggregation

Pivot monthly revenue by category using conditional aggregation, generating column lists dynamically for any date range.

SqlData Integrity

Code

sqlsnippet
24 lines
-- 固定月份的手写透视: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

FAQ

Name the tables involved in this file.
`monthly_revenue` — referenced directly, no join needed.