首页 > 解决方案 > 如何在 SQL Server 中合并两条记录并对一列求和

问题描述

有一个包含两列的简单表。Col1 就像一个标识符。

我想对具有相同 Col1 值的行数求和。并更新当前表。

当前表:

Col1 | Quantity
-----+----------
12   | 3
15   | 7
12   | 2

我需要的UPDATED表是将 Col1=12 的两行的数量相加(例如 .. WHERE Col1=12 ...)并将它们合并为一行:

Col1 | Quantity
-----+----------
12   | 5
15   | 7

在 SQL Server 查询中怎么可能?

请注意,我需要更新表格。不只是选择行。

标签: sqlsql-server

解决方案


使用sum()聚合group by

with cte as 
(
select col1,quantity,row_number() over(partition by col1 order by quantity) as rn
from tablename
)

    update a set a.quantity=b.qty
    from cte a 
    inner join
    (select col1, sum(quantity) as qty
        from tablename
        group by col1
    )b on a.col1=b.col1 where rn=1

delete a from tablename a
join
(
select col1,quantity,row_number() over(partition by col1 order by quantity) as rn
    from tablename
)b on a.col1=b.col1 and rn>2

推荐阅读