我有三个表,我需要从中添加一个聚合(sum(totalcost)到另一个表的列。我还需要计算总成本,以便根据另一个表中的行号添加或减去最后,我需要确定订单的项目类型作为聚合的最终条件
Order table
Order Num Material Cost Service Cost Total Cost
11111 200.00 220.00 210.00
11112 0.00 0.00 0.00
OrderCost Table
Order Num Costline Cost Purchase Order ID % of PO Cost
11111 1 100.00 P00001 50%
11111 1 110.00 P00002 50%
11112 2 100.00 P00001 50%
11112 2 110.00 P00002 50%
OrderDetails Table
Order ItemReq ItemType Cost
11111 M10001 MATERIAL 200.00
11111 S10001 SERVICE 220.00
将订单添加到OrdeCost表时,需要以下内容:
结果
Order ID TotMatCost TotServCost TotCost
11111 100.00 110.00 210.00
11112 100.00 110.00 210.00
修改后的代码
select order.wonum, order.wopriority, order.worktype, order.estintlabcost,order.estoutlabcost, order.estlabcost,
order.estmatcost, order.estservcost, order.esttoolcost, order.actintlabcost, order.actoutlabcost, order.actlabcost,
order.actmatcost-
(select sum(loadedcost)*
(CASE costlinenum
WHEN 1 THEN 1
ELSE -1 END) NUMLINES
from cost, OrdedetalisL
where cost.cc_wonum = Ordedetalisl.wonum and Ordedetalisl.linetype = 'MATERIAL'
AND cost.percentage<100 and cost.cc_wonum = 'H1006'
group by cc_wonum, costlinenum) actmatcost,
order.actservcost-
(select sum(loadedcost)*
(CASE costlinenum
WHEN 1 THEN 1
ELSE -1 END) NUMLINES
from cost, WPSERVICE
where cost.cc_wonum = wpservice.wonum and wpservice.linetype = 'SERVICE'
AND cost.percentage<100 and cost.cc_wonum = 'H1006'
group by cc_wonum, costlinenum) actservcost, order.acttoolcost,(order.estintlabcost + order.estoutlabcost + order.estlabcost+order.estmatcost + order.estservcost + order.esttoolcost +
order.actintlabcost + order.actoutlabcost +
(select sum(loadedcost)*
(CASE costlinenum
WHEN 1 THEN -1
ELSE 1 END) NUMLINES
from cost
where percentage<100 and cc_wonum = 'H1006'
group by cc_wonum, costlinenum)) totalcost
from order where order.wonum = 'H1006'