1/25/2018 - 12:53 PM

Good subquery example

A useful real-world example, illustrating a use for subqueries and how they can be used in analysing sales trends and in this case, analysing low performing products.

-- The example:

-- select product name, sum of the amount paid rounded up
select name, round(sum(amount_paid) / 
--...divided by (sum of the amount paid for every other item) multiplied by 100, percentage rounded to 2 decimal places
(select sum(amount_paid) from order_items) * 100.0, 2) as pct 
from order_items
group by 1 -- group by product name
order by 2 desc; -- order by the percentage, descending(high->low)