Skip to content
Advertisement

Need to combine two rows that are exactly the same with the exception of one column

I have a large database where each month more data is added, in this database if a new user is added it creates a new row. The issue I have is that due to spelling error in the past which I have since corrected. The data is appearing as one row. What I need is for both rows to be combined under the one username.

I essentially would like to combine the totals for both of these rows. So in your example I would like all totals in the wrong row ‘Jhon Smith’ to be added to the correct row ‘John Smith’. I could then delete the row that is wrong once I knew the values were all accounted for.

+------------------------------------------+------------+-------+----------+----------+
|                                          |  Username  | Miles |   Car    | Expenses |
+------------------------------------------+------------+-------+----------+----------+
| Correctly spelled row                    | John Smith |   200 | Peugeaut |     1000 |
| Incorrectly spelled row                  | Jhon Smith |    17 | Peugeaut |      500 |
| Total of both rows (what I want to show) | John Smith |   217 | Peugeaut |     1500 |
+------------------------------------------+------------+-------+----------+----------+

Thanks in advance for any help.

Connor

Advertisement

Answer

It sounds like all you need is an inner join on the two rows and to add the (however many) columns together, something along the lines of

update t set
    t.col1 = t.col1 + t2.col1,
    t.col2 = t.col2 + t2.col2,
    <rinse repeat>
    ...
from table t join table t2 on t2.Id=67890 <-- PK of the row to delete
where t.Id=12345 <-- PK of table, 12345 is the row you want to keep
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement