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

时间:2018-10-19 09:17:59

标签: sql sql-server merge upsert table-valued-parameters

源表

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

目标表

Id, Name, hits
1   A     NULL

合并后

Id, Name, hits
1   A     60
2   A     10

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

1 个答案:

答案 0 :(得分:2)

尝试以下

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)