合并SQL 2012中的重复行

时间:2016-05-10 12:30:22

标签: sql sql-server tsql stored-procedures

这是我的表结构,我尝试创建一个存储过程,获取此信息的摘要。

Part Number  Weight    Type    
----------------------------
234           120       P     
212           45        P
234           110       P
234           100       C

具有相同零件编号和类型的零件我想合并记录并得到重量的总和,输出如下。

Part Number  Weight    Type    
----------------------------
234           230       P     
212           45        P
234           100       C

1 个答案:

答案 0 :(得分:6)

这只是一个简单的GROUP BY SUM()

Select  [Part Number], Sum([Weight]) As [Weight], [Type]
From    YourTable
Group By [Part Number], [Type]

如果您想将其设为STORED PROCEDURE,则CREATE语法如下:

Create Procedure spGetTotalWeightsByPartAndType --Or whatever you want to name it
As Begin
    Select  [Part Number], Sum([Weight]) As [Weight], [Type]
    From    YourTable
    Group By [Part Number], [Type]
End