Okay, so I'm woking on a database, where I have basically a list of ownerships. And sometimes I receive almost duplicate rows, differing only in the amount of the property. I'd like to merge them into one, setting the amount as the sum of the two. Example:
Name Surname Amount
Ann Evans 4
Ann Evans 7
And I'd like to have just:
Ann Evans 11
How do I merge two rows having a common tuple?
Use SUM()
aggregate function along with GROUP BY
clause:
SELECT Name,
Surname,
SUM(Amount) AS total_amount
FROM tbl
GROUP BY
Name,
Surname;
UPD. Michał Szydłowski : Okay, but I don't want to select, I want to run an update query, that will permanently modify the table.
The best option I see here, is to use INSERT INTO ... SELECT
:
CREATE TABLE temp_tbl LIKE tbl;
INSERT INTO temp_tbl (Name, Surname, Amount)
SELECT Name,
Surname,
SUM(Amount)
FROM tbl
GROUP BY
Name,
Surname;
TRUNCATE tbl;
INSERT INTO tbl (Name, Surname, Amount)
SELECT Name,
Surname,
Amount
FROM temp_tbl;
将聚合函数SUM()与GROUP BY
子句一起使用,按所需的列数和结果分组
select Name,Surname,sum(Amount) as Amount from table group by Name,Surname
Try this:
SELECT Name, SurName, SUM(Amount) as TotalAmount FROM myTable GROUP BY Name, SurName
Hope this help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.