CASE Conditional Pivoting
Rotate rows into columns with conditional aggregation — CASE inside SUM — so a variable number of rows becomes a fixed number of fields.
Code
-- 行转列:每个 region 一行,每种渠道一列
SELECT
region,
SUM(CASE WHEN channel = 'web' THEN revenue ELSE 0 END) AS web_revenue,
SUM(CASE WHEN channel = 'mobile' THEN revenue ELSE 0 END) AS mobile_revenue,
SUM(CASE WHEN channel = 'api' THEN revenue ELSE 0 END) AS api_revenue,
-- 布尔透视:达成目标的订单数与总数
COUNT(*) FILTER (WHERE revenue >= 1000) AS big_orders,
COUNT(*) AS all_orders
FROM sales
GROUP BY region
ORDER BY region;Inside the snippet
What runs is SELECT, with sales as the object involved.
Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Putting it to use
Run the statement against the sales table.
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
- Which tables or CTEs does it reference?
- The references are `sales`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.