Ajking11
Ajking11

Reputation: 67

Mysql DISTINCT and COUNT query

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.

Upvotes: 1

Views: 85

Answers (2)

geeksal
geeksal

Reputation: 5016

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`;

Upvotes: 0

Jan
Jan

Reputation: 13858

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`

Upvotes: 2

Related Questions