Express grouped calculations in SQL
Many tasks described as mapping and reducing rows can be written as a SELECT followed by GROUP BY. Expressions calculate the values of interest, while aggregate functions combine rows sharing the grouping key.
CREATE TABLE usage_samples(account_id INTEGER, quantity INTEGER, unit_price INTEGER);
INSERT INTO usage_samples VALUES (1, 2, 5), (1, 3, 5), (2, 1, 9);
SELECT account_id, sum(quantity * unit_price) AS total
FROM usage_samples
WHERE quantity > 0
GROUP BY account_id
ORDER BY account_id
FORMAT csv;This example produces one total per account. The filter selects participating rows before aggregation. Use HAVING when a predicate depends on the completed group total, and choose types appropriate for the numeric range and exactness required by the calculation.
This is ordinary SQL over the selected data sources, not a distributed MapReduce execution service. If input lives elsewhere, import or read it through a documented source first. Check join cardinality before grouping because duplicated matches can multiply a total even when the aggregate itself is correct.
See GROUP BY, HAVING, aggregates and input sources.