Aggregate Functions
The extension provides aggregate functions that preserve currency type safety.
Same-Currency Aggregates
Section titled “Same-Currency Aggregates”These functions require all values to have the same currency:
monetary_sum
Section titled “monetary_sum”Sums monetary values:
monetary_avg
Section titled “monetary_avg”Calculates the average:
monetary_min / monetary_max
Section titled “monetary_min / monetary_max”Finds minimum and maximum values:
Currency Mismatch Errors
Section titled “Currency Mismatch Errors”Aggregating different currencies throws an error:
To aggregate mixed currencies, use monetary_sum_converted.
Converting Aggregates
Section titled “Converting Aggregates”monetary_sum_converted
Section titled “monetary_sum_converted”Sums values after converting to a target currency:
monetary_sum_converted(value, target_currency, rate) → monetaryFor dynamic rates from an exchange table:
-- Load ratesCREATE TABLE rates AS SELECT * FROM ecb_exchange_rates();
-- Join to get rates for conversionWITH prices AS ( SELECT '100 EUR'::monetary AS price, 'EUR' AS curr UNION ALL SELECT '100 USD'::monetary, 'USD' UNION ALL SELECT '100 GBP'::monetary, 'GBP')SELECT monetary_sum_converted( price, 'EUR', COALESCE(r.rate, 1.0)) AS total_eurFROM prices pLEFT JOIN rates r ON r.currency_to = p.curr;Summary
Section titled “Summary”| Function | Same Currency | Description |
|---|---|---|
monetary_sum(m) | Required | Sum values |
monetary_avg(m) | Required | Average values |
monetary_min(m) | Required | Find minimum |
monetary_max(m) | Required | Find maximum |
monetary_sum_converted(m, target, rate) | No | Sum with conversion |
Group By
Section titled “Group By”Aggregate functions work with GROUP BY: