Categories
MySQL

Complex SQL query using SUM and GROUP BY

Got this question as part of a skills evaluation test. It requires a query to calculate summary-like data from tables in an order system type database.

  1. There is an `orders` table that consists of an order_no and customer_id fields.
  2. Also, an `order_items` table that consists of order_item_id, order_id, product_id, qty, unit_price and total.
  3. unit_price is the price of an individual order item and total is unit_price * qty.
  4. Write a SQL query that will display all orders with the following fields listed (where the total_value field is the sum of all of the order items totals for each order: order_no, customer_id, total_value

My tested solution:

SELECT `o`.`order_no`, `o`.`customer_id`, SUM(`oi`.`total`) AS `total_value`
FROM `orders` `o` JOIN `order_items` `oi` ON `o`.`order_no` = `oi`.`order_id`
GROUP BY `oi`.`order_id`
ORDER BY `o`.`order_no`;

By foxbeefly

PHP / MySQL Developer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.