如何将重复的行更新为一行

How to Update duplicated Rows into One Row

我需要合并相同的条目并逐行汇总数量。例如:

glass type  height   width    quantity
---------------------------------------
4DC          1500     600        1
4DC          1500     600        2
4DC          1200     500        5
4DC          1200     500        2
3DC          1500     600        2

将是:

glass type   height   width   quantity
---------------------------------------
4DC           1500     600      3
4DC           1200     500      7
3DC           1500     600      2

但我不需要任何 select 查询,我需要更新 table 并删除重复的行并用总数量更新其中一个。

我该怎么做?

我的建议是替换 table:

select glasstype, height, width, sum(quantity) as quantity
into temp_t
from t
group by glasstype, height, width;

truncate table t;  -- backup first!

insert into temp_t (glasstype, height, width, quantity)
    select glasstype, height, width, quantity
    from temp_t;

drop table temp_t;

或者,您可以分两步完成此操作:

with toupdate as (
      select t.*, sum(quantity) over (partition by glasstype, height, width) as new_quantity
      from t
     )
update toupdate
    set quantity = new_quantity;

with todelete as (
      select t.*,
             row_number() over (partition by glasstype, height, width order by glasstype) as seqnum
      from t
     )
delete from todelete
    where seqnum > 1;

我会做与 Gordon 类似的事情,但是,我会重命名对象:

SELECT GlassType,
       Height,
       Width,
       SUM(Quantity)
INTO dbo.NewTable
FROM dbo.YourTable
GROUP BY GlassType,
         Height,
         Width;
GO
EXEC sp_rename N'dbo.YourTable',N'OldTable';
GO
EXEC sp_rename N'dbo.NewTable',N'YourTable';
GO

这意味着您仍然拥有旧 table 的副本,如果您有任何外键,您将无法 TRUNCATE。但是,您必须在新 YourTable

上重新创建任何现有的约束和索引

然后我会在您的 table 上创建一个唯一约束,这样您以后就不会重复。

ALTER TABLE dbo.YourTable ADD CONSTRAINT UC_TypeHeightWidth UNIQUE (GlassType,Height,Width);