Advanced aggregation

Draft

Advanced aggregation is still the same idea: shape many rows into fewer rows, but with sharper tools for filters and time buckets.

HAVING

HAVING filters groups, while WHERE filters rows before grouping.

SELECT status, COUNT(*) AS payments
FROM payments
GROUP BY status
HAVING COUNT(*) > 1
ORDER BY status;
Loading plan...

FILTER

FILTER lets different aggregates count different subsets in one query.

SELECT
  COUNT(*) FILTER (WHERE status = 'paid') AS paid,
  COUNT(*) FILTER (WHERE status = 'failed') AS failed
FROM payments;
Loading plan...

Group by time

date_trunc turns timestamps into buckets such as day, month, or year.

SELECT date_trunc('day', created_at) AS day, SUM(amount_cents) AS total_cents
FROM payments
WHERE status = 'paid'
GROUP BY day
ORDER BY day;
Loading plan...

Try Yourself

Loaded Database:advanced-aggregation.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Return paid revenue grouped by day.
2.Return total rows and paid rows using COUNT with FILTER.

What We Learned

  • HAVINGfilters groups after GROUP BY.
  • FILTERapplies a condition to one aggregate call.
  • date_truncrounds timestamps down to a time bucket.