使用CASE进行多级多表聚合计算

时间:2016-06-15 12:45:39

标签: sql-server tsql

我有三个表,我需要从中添加一个聚合(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表时,需要以下内容:

  1. 按订单ID汇总的物料成本
  2. 按订单ID
  3. 汇总的服务费用
  4. 需要从现有记录的OrderDetail材料成本中减去材料成本
  5. 需要从现有记录的OrderDetail服务成本中减去服务成本
  6. 需要将汇总材料成本添加到不在OrderDetail表中的订单ID的结果中
  7. 需要将汇总服务成本添加到订单ID中不在OrderDetail表中的结果
  8. 结果

    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'
    

0 个答案:

没有答案
相关问题