在 SQL 中自行加入以更新 table

Self join to update table in SQL

我有以下 table:

Category Qty Orders Level
Product 0
Part 1 2 4 1
Part 2 3 5 1
Part 1.1 4 6 2
Part 1.2 5 7 2

如何用数量和订单的总和(不包括级别 0 的数量和订单)更新上面 table 的 0 级行?

Category Qty Orders Level
Product 14 (i.e. 2+3+4+5) 22 (i.e. 4+5+6+7) 0
Part 1 2 4 1
Part 2 3 5 1
Part 1.1 4 6 2
Part 1.2 5 7 2

您可以使用使用子查询或 CTE 的 Update 语句,但我认为实际上您的 table 没有任何 Id(例如一个 id link 所有这些部分* 到特定产品。无论如何,原样:

Update myTable
   set Qty = agg.Qty, Orders=agg.Orders 
from (Select Sum(Qty) Qty, Sum(Orders) Orders from myTable where level > 0) agg
where level=0;

DBFiddle demo

Update TableName
set     Qty = (select Sum(Qty) from TableName where Level<>0),
        Orders = (select Sum(Qty) from TableName where Level<>0 )
where Level = 0

UPDATE yourtablename set qty = 
(Select sum(qty) from yourtablename
Where level != 0),
orders = 
(Select sum(orders) from yourtablename
Where level != 0) 
where level = 0