MERGE TVP + 在更新记录时对列求和

MERGE TVP + sum the column while updating a record

来源Table

Id, Name, hits
1   A     10    
1   A     20
1   A     30
2   A     10

目标Table

Id, Name, hits
1   A     NULL

合并后

Id, Name, hits
1   A     60
2   A     10

以上可能吗?使用 Merge 语句 ?

试试下面

MERGE     targetTable AS [pi]
USING     ( 
               SELECT id,name,sum(hits) as hits from sourcetable
               GROUP BY id,name
          ) AS src (id,name,hits) ON src.id= [pi].id and scr.name=pi.name
WHEN      MATCHED 
               THEN UPDATE SET [pi].hits= src.hits
WHEN      NOT MATCHED 
               THEN INSERT values (src.id, src.name,hits)