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.

SqlData Integrity

Code

snippet
-- 行转列:每个 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

FAQ

Which tables or CTEs does it reference?
The references are `sales`.