我们有多个具有相同密钥(Item)的记录,我们希望使用更新将所有记录的总和减少到一条记录。目标记录是这些记录之一。我们也希望在多个项目上做到这一点。 示例(Original Image):
+ -------- + --------- + ---- + ------ + ---- + ------- + ------------ + ------ + ------ + ------- + ----------- + ------- + --------- +
| Location | Financial | Real | Orders | Free | Ordered | Average Sale | Result | Result | StockNo | Stock Costs | Value | Warehouse |
+ -------- + --------- + ---- + ------ + ---- + ------- + ------------ + ------ + ------ + ------- + ----------- + ------- + --------- +
| 106 | 84 | 0 | 45 | -45 | 0 | 0 | 84 | 0 | 0000000 | 50.22 | 0.00 | 0 |
| 106 | 0 | 4 | 0 | 4 | 0 | 0 | 0 | 4 | 1004424 | 50.22 | 200.88 | 0 |
| 106 | 0 | 80 | 0 | 80 | 0 | 0 | 0 | 80 | 0000001 | 50.22 | 4017.60 | 0 |
+ -------- + --------- + ---- + ------ + ---- + ------- + ------------ + ------ + ------ + ------- + ----------- + ------- + --------- +
我已经尝试过:
update Itemstock
Set queuequantity = (Select Sum(IS_2.queuequantity) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
reservationquantity = (Select Sum(IS_2.reservationquantity) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
warehousequantity = (Select Sum(IS_2.warehousequantity) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
averageout = (Select Sum(IS_2.averageout) from itemstock IS_2 where (IS_2.item=item) and bookyear=2017),
purchasequantity = (Select Sum(IS_2.purchasequantity) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
financialamount = (Select Sum(IS_2.financialamount) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
financialresult = (Select Sum(IS_2.financialresult) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
technicalquantity = (Select Sum(IS_2.technicalquantity) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
technicalamount = (Select Sum(IS_2.technicalamount) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017),
technicalresult = (Select Sum(IS_2.technicalresult) from itemstock IS_2 where (IS_2.item=item) and IS_2.bookyear=2017)
where item=(select objectid from item where Itemgroup=15900239)
and Stockno=0
and bookyear=2017`
然而,这会产生以下错误:
单行选择
中的多行
我理解为什么,但无法找到解决方案。我不是SQL专家。
答案 0 :(得分:2)
尝试使用聚合一次并在连接时执行更新,而不是所有相关子查询。此外,在where子句中使用IN
,因为子查询可能返回多行:
update a
set a.queuequantity = b.queuequantity,
a.reservationquantity = b.reservationquantity,
...
from itemstock a
join (
select item,
Sum(queuequantity) as queuequantity,
Sum(reservationquantity) as reservationquantity,
...
from itemstock
where bookyear = 2017
group by item
) b on a.item = b.item
where a.item in (
select objectid
from item
where Itemgroup = 15900239
)
and a.Stockno = 0
and a.bookyear = 2017