使用CTE删除重复项时,有什么方法可以汇总重复行?

时间:2019-02-21 11:36:57

标签: sql-server duplicates aggregate-functions common-table-expression

我有一个包含重复的ItemId的表。我正在使用CTE删除重复的记录,并为每个项目仅保留一个记录。我可以使用以下查询成功实现此里程碑:

Create procedure sp_SumSameItems
as
begin
    with cte as (select a.Id,a.ItemId,Qty, QtyPrice, 
    ROW_NUMBER() OVER(PARTITION by ItemId ORDER BY Id) AS rn from tblTest a)
    delete x from tblTest x Join cte On x.Id = cte.Id where cte.rn > 1
end

实际的问题是我想Sum QtyQtyPrice,然后再删除重复的记录。我应该在哪里添加Sum函数?

问题图示:

enter image description here

3 个答案:

答案 0 :(得分:3)

您不能将updatedelete语句一起使用,而需要update之前:

update t
     set t.qty = (select sum(t1.qty) from table t1 where t1.itemid = t.itemid);

答案 1 :(得分:0)

CTE仅对一条语句有效,因此您将需要运行cte两次,一次求和然后删除,或者可以将CTE的结果放入临时表中,然后使用临时表求和,然后删除原始表中的记录。

答案 2 :(得分:0)

在第一级,删除重复记录后,您必须更新Qty和QtyPrice。

给出示例:

CREATE PROCEDURE Sp_sumsameitems 
AS 
  BEGIN 
      WITH cte1 
           AS (SELECT a.id, 
                      a.itemid, 
                      Sum(qty)     Qty, 
                      Sum(qtyprice)QtyPrice, 
               FROM   tbltest a 
               GROUP  BY a.id) 
      UPDATE x 
      SET    x.qty = c.qty, 
             x.qtyprice = c.qtyprice 
      FROM   tbltest x 
             JOIN cte1 c 
               ON x.id = cte.id 

      WITH cte 
           AS (SELECT a.id, 
                      a.itemid, 
                      qty, 
                      qtyprice, 
                      Row_number() 
                        OVER( 
                          partition BY itemid 
                          ORDER BY id) AS rn 
               FROM   tbltest a) 
      DELETE x 
      FROM   tbltest x 
             JOIN cte 
               ON x.id = cte.id 
      WHERE  cte.rn > 1 
  END