I’m looking for a single MySQL query (subqueries are fine) that will get a distribution of units per order over the past year in the following format:
units_per_order | number_of_orders | percent_of_total --------------------------------------------------------------------- 1 | 7500 | 55% 2 3 4 5 6-10 10-20 30-50 50–100 100+
EDIT:
Tables and necessary columns to query against:
Table: orders Fields: orders_id, date_purchased Table: orders_products Fields: orders_id, products_quantity
This is what I have right now:
SELECT COUNT(*) AS cnt, qty FROM (
SELECT SUM(products_quantity) as qty, orders_id
FROM orders_products op LEFT JOIN orders o USING (orders_id)
WHERE date_purchased LIKE '2012%'
GROUP BY orders_id
) AS new_table WHERE qty != 0 GROUP BY qty ORDER BY qty
Any ideas?
Ok, here’s what I ended up with. Please advise if you see any way to make it more efficient.