0

I am making a shopping cart. Selected items are stored inside a database based on a search query.

How I can add the quantity for rows in case sku, type and color are the same values?

example:

sku  type   color  quantity
---------------------------
1    type1  blue   5
1    type1  blue   2
2    type1  blue   5
1    type1  green  5

my new rows should be:

sku  type   color  quantity
---------------------------
1    type1  blue   7
2    type1  blue   5
1    type1  green  5

Notice the first row quantity is now 7.

How can this be done? I tried GROUP BY, but didn't know how to make it dynamic to match all.

3 Answers 3

2
  SELECT sku,type,color, 
         SUM(quantity) 
    FROM table 
GROUP BY sku,type,color
Sign up to request clarification or add additional context in comments.

5 Comments

how i can update the tables after ward with those values? and remove the other duplicated now..
INSERT INTO table2 (select_statement_above); DROP table1;
You're either using a wrong ER or a bad code if this happens and you need to fix it.
dropping the table is not a solution, any good cleanup process?
insert those to the same table, delete any rows below inserted_id
1
SELECT sku, type, color, sum(quantity)
FROM theTable
GROUP BY  sku, type, color

That will do it.

4 Comments

how i can update the tables afterward with those values? and remove the others.. remember i want to clean the table
Why do you want to alter the table? Just use these results.
the purpose is to clean up my table
if the table is not being updated, then run this query, and put the results into a new, second table. Then empty out the old table and replace it with the new table's results. This is not great, since you're changing the meaning of the table, and not something to do regularly. but if it's a one-time cleanup, go for it.
0
CREATE TEMPORARY TABLE IF NOT EXISTS tmpTable LIKE dataTable

DELETE FROM tmpTable

Insert into tmpTable
select sku,type,color,sum(quantity) from dataTable
group by sku,type,color

DELETE FROM dataTable

INSERT INTO dataTable
SELECT * FROM tmpTable

3 Comments

how i can update the tables afterward with those values? and remove the others.. remember i want to clean the table
can't completely understand your question. delete from table1; insert into table1 select sku,type,color,sum(quantity) from ... group by sku,type,color? Or you want to replace data in table right inplace?
i have a messy table that i want to clean it up, where the result is exactly the same command u made.

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.