For example lets take Northwind. I want to use CASE clause to create categories by comparing units_in_stock with its AVG value and place this value in multiple BETWEEN clauses. That is what I have got:
SELECT product_name, unit_price, units_in_stock,
CASE
WHEN units_in_stock > (SELECT AVG(units_in_stock) + 10 FROM products) THEN 'many'
WHEN units_in_stock BETWEEN (SELECT AVG(units_in_stock) - 10 FROM products) AND (SELECT AVG(units_in_stock) + 10 FROM products) THEN 'average'
ELSE 'low'
END AS amount
FROM products
ORDER BY units_in_stock;
According to Analyze tool in pgAdmin AVG(units_in_stock) was calculated three times. Is there a way to reduce amount of calculations?