简体   繁体   English

SQL合并的行相差1参数

[英]SQL merging rows differing by 1 parameter

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: SUM()聚合函数与GROUP BY子句一起使用:

SELECT Name, 
       Surname, 
       SUM(Amount) AS total_amount
  FROM tbl 
GROUP BY 
       Name, 
       Surname;

UPD. 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. MichałSzydłowski :好的,但是我不想选择,我想运行一个更新查询,它将永久修改表。

The best option I see here, is to use INSERT INTO ... SELECT : 我在这里看到的最佳选择是使用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. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM