将两行合并为一行并对列求和

时间:2017-03-30 17:42:15

标签: sql-server sql-server-2008

这不是要求如何使用SUM()和GROUP BY

我在tableA中有两行

ID VALUE
1  100
1  200

我想要tableA:

ID VALUE
1  300

请注意,我想

  1. 删除tableA中的原始两条记录
  2. 并将其替换为tableA
  3. 中的新记录

    这与merge功能有关吗?

    我只想在tableA上工作,不想创建任何新表。

1 个答案:

答案 0 :(得分:2)

MERGE

怎么样?
;with cte as (
    select t.*, 
    row_number() over (partition by id order by id) as rn,
    sum(value) over (partition by id) as total_value
    from your_table t
)
merge into cte as t
using cte as t2
on (
    t.id = t2.id
    and t.rn = t2.rn
    and t.rn = 1
)
when matched then update set t.value = t2.total_value
when not matched by source then delete;

Demo