使用特定逻辑合并 SQL 中的行

Merge rows in SQL with specific logic

我有以下 table:

ProductCategory Qty Price
Wood 2 40
Metal 2 20
Glass 2 40
Other 2 30
Misc 3 10
Extra 5 20

我想将其他、杂项和额外类别合并为“其他”类别。 Qty 和 Price 可以有 Other、Misc 和 Extra 类别的总和。

Product Category Qty Price
Wood 2 40
Metal 2 20
Glass 2 40
Extra 10 (i.e. 2+3+5) 60 (i.e. 30 + 10 + 20)

其中一种方法是:

-- Create temp table to hold sum of Other, Misc, Extra

DECLARE @Qty AS INT, @Price AS INT

SELECT @Qty = Sum(Qty), @Price = Sum(Price) 
FROM Product 
WHERE ProductCategory IN ('Other', 'Extra', 'Misc')

DELETE FROM Product 
WHERE ProductCategory IN ('Other', 'Extra', 'Misc')

INSERT INTO Product (ProductCategory, Qty, Price) 
VALUES ('Extra', @Qty , @Price)

使用 SQL 最简单的方法是什么?

您可以使用 case 表达式group by

来做到这一点
select v.ProductCategory, Sum(qty) Qty, Sum(price) Price
from t
cross apply (values(
    case when productcategory in ('Misc','Extra') then 'Other' /*or Extra...?*/
    else ProductCategory 
  end)
)v(ProductCategory)
group by v.ProductCategory

Example fiddle

使用输出到温度 table

declare @tmp table(Qty int, Price int);

delete tbl
  output deleted.qty, deleted.price into @tmp (Qty, Price)
where ProductCategory in ('Misc','Other');

update t
  set Qty = t.Qty + u.qty , Price = t.Price + u.Price
from tbl t
join (select sum(Qty) qty, sum(Price) Price
      from @tmp) u
      on t.ProductCategory = 'Extra';

db<>fiddle