snippetMinor
How can I merge duplicate rows in a single table?
Viewed 0 times
rowscanmergeduplicatesinglehowtable
Problem
I have a table with duplicate barcodes (
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
Example:
I want it to read:
How can I do this?
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 17I want it to read:
Row 1 1 610708542209 -11 36
Row 2 2 610708542209 -3 17How can I do this?
Solution
This is what's known as an aggregate query,
Using
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.Code Snippets
SELECT cart, barcode,
SUM(counted_in) AS counted_in,
SUM(counted_out) AS counted_out
FROM tbl
GROUP BY cart, barcode;Context
StackExchange Database Administrators Q#130727, answer score: 4
Revisions (0)
No revisions yet.