tags:

views:

28

answers:

1

A client needs a sales report by country state/province. There is an orders table that stores the customer's country and state/province, and there is an orders_products table that stores the order to product association and the product's price.

The client wants the following statistics per country & state/province: total sales, % sales, avg order value.

I hope I have provided enough information. If you need anything else, please let me know.

Thanks!

A: 

== Assumed Tables ==

orders (id, country_id, state_id)

orders_products (id, order_id, product_id, price)

== Queries ==

Total sales:

SELECT country_id, state_id, SUM(price)
FROM orders_products op, orders o 
WHERE op.order_id = o.id 
GROUP BY country_id, state_id

Average Sale Amount:

SELECT country_id, state_id, AVG(price) * COUNT(order_id) 
FROM orders_products op, orders o 
WHERE op.order_id = o.id 
GROUP BY country_id, state_id, order_id

The % of total sales per state/country:

SELECT country_id, state_id, SUM(price) * 100 /
    (SELECT SUM(price) FROM orders_products op2) 
FROM orders_products op, orders o 
WHERE op.order_id = o.id 
GROUP BY country_id, state_id
Justin Giboney