This is a simplified version of a query I have. Say for each customer that has made an order, I want to know what percentage of their total order value was for green items.
There can’t be multiple items in an order, but it’s possible for the order value to be zero so I want to avoid division errors. (And no, I am not able to change the database in any way.)
What’s the best way to do this? EDIT: Omitting zero-totals is fine actually, hence accepted answer.
SELECT order.customer, SUM ( CASE items.color WHEN 'Green' THEN order.value ELSE 0 END ) * 100 / sum(order.value) AS percentage, SUM(order.value) AS total_value FROM orders INNER JOIN item ON order.item_id = item.item_id GROUP BY order.customer
Add
After your group by