Distinct counts per group
One query, several distinct counters per group: active days, statuses, products.
The task
You want, per customer, on how many different days they ordered and how many distinct statuses their orders passed through.
The snippet
Written for PostgreSQL.
SELECT customer_id,
COUNT(DISTINCT CAST(order_date AS date)) AS active_days,
COUNT(DISTINCT status) AS statuses_used,
COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
ORDER BY active_days DESC;
Cómo funciona
COUNT(DISTINCT expr) deduplicates the expression inside each group before counting, and you can use it several times in one SELECT. Casting the timestamp to a date collapses same-day orders into one day; that cast works on PostgreSQL, MySQL and SQL Server. On Oracle CAST(... AS DATE) keeps the time, so use TRUNC(order_date), and on SQLite CAST(... AS date) turns '2026-06-01 12:00:00' into the number 2026, so use date(order_date). PostgreSQL, MySQL, SQL Server and SQLite reject COUNT(DISTINCT) inside OVER (Oracle allows it without an ORDER BY), so pre-aggregate in a subquery when you need a running distinct count.
Variations
Distinct count as a window metric
WITH per_day AS (
SELECT customer_id, CAST(order_date AS date) AS day,
SUM(amount) AS day_total
FROM orders
GROUP BY customer_id, CAST(order_date AS date)
)
SELECT customer_id, day, day_total,
COUNT(*) OVER (PARTITION BY customer_id
ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW) AS active_days_so_far
FROM per_day;
Questions that come up
Distinct counts are slow on huge tables. Any alternative?
Yes, approximate counts. SQL Server 2019+ and Oracle 12c+ have APPROX_COUNT_DISTINCT, built on HyperLogLog with an error of a few percent, and PostgreSQL gets the same from the hll extension. MySQL and SQLite have no built-in equivalent.
Keep reading
Related on SQLly
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.