// SQL snippet

Conditional sums (SUM IF)

CASE picks the rows, SUM adds them. The same expression is what a CASE pivot is built from.

Main statement
All engines

The task

You want, per customer, the shipped revenue and the returned revenue as a negative number, in one grouped query.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT customer_id,
       SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_amount,
       SUM(CASE WHEN status = 'returned' THEN -amount ELSE 0 END) AS returned_amount
FROM orders
GROUP BY customer_id
ORDER BY customer_id;

工作原理

Each CASE transforms the rows into a per-condition measure: matching rows contribute their amount (negated for returns), everything else contributes 0, and the grouped SUM collapses it. Any expression can live inside the THEN, so the same pattern handles net amounts, VAT buckets or weighted scores. Like count-if, engines with FILTER make it read nicer.

Variations

FILTER clause (PostgreSQL, SQLite)

PostgreSQL SQLite
SELECT customer_id,
       SUM(amount) FILTER (WHERE status = 'shipped') AS shipped_amount,
       SUM(-amount) FILTER (WHERE status = 'returned') AS returned_amount
FROM orders
GROUP BY customer_id;

Questions that come up

Why ELSE 0 and not ELSE NULL?

For SUM they give the same total, except that a group with no matching rows sums to NULL rather than 0 (the FILTER variant has the same NULL behaviour). For AVG and MIN they differ: ELSE 0 drags averages down and makes 0 the minimum, while ELSE NULL computes those aggregates over the matching rows only.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.