Question

I have a table and I would like to merge the data of two rows having the same name, like this:

id | name    | price | priced

1  | Samsung | 100   | 0

2  | Samsung | 0     | 500

I'd like the final input to be:

id               | name    | price | priced

(doesn't matter) | Samsung | 100   | 500 
Était-ce utile?

La solution

Try this:

SELECT MAX(id) as id, name,MAX(price) as price, MAX(priced) as priced
FROM TableName
GROUP BY name

To insert into a table:

INSERT INTO Table2 VALUES
(SELECT MAX(id) as id, name,MAX(price) as price, MAX(priced) as priced
FROM TableName
GROUP BY name)

EDIT

As you say, to merge (insert new and delete others)

INSERT INTO TableName VALUES
(SELECT MAX(id)+1 as id, name,MAX(price) as price, MAX(priced) as priced
FROM TableName
GROUP BY name)

--Now deleting others
DELETE T1 FROM TableName T1, TableName T2 WHERE T1.id < T2.id AND T1.name = T2.name

Autres conseils

you wanna this?

 select id , name,
 sum(price) as price, sum(priced) as priced from table1
 group by name

I understand you want to add the prices not get the maximum. I think you should make a new table 'table2' and add rows to it the following way :

INSERT INTO table2 Values (
SELECT
  name,
  SUM(price),
  SUM(priced)
FROM table1
GROUP BY name )

Then delete table1. This way you will add the rows with the same name from table1

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top