1

im having issues getting a query to output how i want,

SELECT 
    `orders`.`item_id`, 
    `products`.`item_code`, 
    `products`.`item_name`, 
    `orders`.`quantity` 
FROM 
    `orders` 
    JOIN `products` ON `orders`.`item_id` = `products`.`id` 
    JOIN `suppliers` ON `products`.`supplier_ref` = `suppliers`.`supplier_ref` 
WHERE 
    `suppliers`.`id` = 159 
    AND `orders`.`order_status` = 'NOTED'

which is returning the results:

item_id item_code item_name            quantity
1271    RA001G    Green Mop Bucket 12L 2
1270    RA001     Blue Mop Bucket 12L  1
1270    RA001     Blue Mop Bucket 12L  1

but i would like it to bring back distinct item_id with the quantity added together how ever when i've tried to add distinct and count i end up only have one line returned.

2
  • 2
    then you should add a group by clause. Commented Feb 12, 2016 at 15:14
  • You want to see " 1270 RA001 Blue Mop Bucket 12L 2" for the output? Commented Feb 12, 2016 at 15:16

2 Answers 2

2

If you want to sum up the quantities for same items, try grouping over item_id. Like this:

SELECT 
    `orders`.`item_id`, 
    `products`.`item_code`, 
    `products`.`item_name`, 
    sum(`orders`.`quantity`) as quantity, 
FROM 
    `orders` 
    JOIN `products` ON `orders`.`item_id` = `products`.`id` 
    JOIN `suppliers` ON `products`.`supplier_ref` = `suppliers`.`supplier_ref` 
WHERE 
    `suppliers`.`id` = 159 
     AND `orders`.`order_status` = 'NOTED'
  GROUP BY `orders`.`item_id`, 
      `products`.`item_code`, 
      `products`.`item_name`
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant thank you so much, i was grouping by item_id, but was then doing COUNT() instead of SUM() which must have been throwing it off
0

Please use group by clause

 SELECT 
`orders`.`item_id`, 
`products`.`item_code`, 
`products`.`item_name`, 
 sum(`orders`.`quantity`) as quantity
 FROM 
  `orders` 
   JOIN `products` ON `orders`.`item_id` = `products`.`id` 
   JOIN `suppliers` ON `products`.`supplier_ref` =   `suppliers`.`supplier_ref` 
WHERE 
 `suppliers`.`id` = 159 AND `orders`.`order_status` = 'NOTED'
group by 
 `orders`.`item_id`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.