我有下表:
| 產品分類 | 數量 | 價格 |
|---|---|---|
| 木頭 | 2 | 40 |
| 金屬 | 2 | 20 |
| 玻璃 | 2 | 40 |
| 其他 | 2 | 30 |
| 雜項 | 3 | 10 |
| 額外的 | 5 | 20 |
我想將其他、雜項和額外類別合并為“其他”類別。數量和價格可以包含其他、雜項和額外類別的總和。
| 產品分類 | 數量 | 價格 |
|---|---|---|
| 木頭 | 2 | 40 |
| 金屬 | 2 | 20 |
| 玻璃 | 2 | 40 |
| 額外的 | 10(即2 3 5) | 60(即 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 執行此操作的最簡單方法是什么?
uj5u.com熱心網友回復:
您可以使用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
示例小提琴
uj5u.com熱心網友回復:
使用 OUTPUT 到臨時表
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<>小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425871.html
上一篇:在T-SQL中拆分列
