How to merge duplicate rows in a single table

duplicationmerge

I have a table with duplicate barcodes (barcode) and carts (cart) and (Quantity_counted_IN) and (Quantity_Counted_out).

I want to merge all duplicate records that have the same barcode and cart number to show only one barcode for that cart number but sum(Quantity_counted_IN) and sum(Quantity_Counted_out) at the same time.

Example:

           cart   barcode         Quantity_Counted_In  Quantity_Counted_Out
 Row 1        1   610708542209                     -7                    20
 Row 2        1   610708542209                     -4                    16
 Row 3        2   610708542209                     -3                    17

I want it to read:

 Row 1        1   610708542209                    -11                    36 
 Row 2        2   610708542209                     -3                    17

How can I do this?

Best Answer

This is what's known as an aggregate query,

SELECT cart, barcode,
       SUM(counted_in) AS counted_in,
       SUM(counted_out) AS counted_out
FROM tbl
GROUP BY cart, barcode;

Using GROUP BY like this returns one record for every unique occurrence of (cart, barcode) and the totals of counted_in and counted_out for each.