使用多个表时,SUM函数无法正常工作

时间:2018-09-04 13:56:54

标签: sql sql-server

当前我正在使用以下代码:

SELECT psparcomp.ps_comp,
  MPA_Desc.Side,
  MPA_Desc.Color_Code,
  MPA_Desc.Description,
  sum(ISNULL(Forecasts.schd_discr_qty, 0)) AS [Order Amount],
  Product_Structure.pt_promo,
  Forecasts.sod_nbr,
  SUM(PaintSched.qty) AS schedamt
FROM MPA_Desc
  LEFT OUTER JOIN psparcomp ON MPA_Desc.MPA_Number = psparcomp.ps_comp
  LEFT OUTER JOIN Forecasts ON psparcomp.ps_par = Forecasts.sod_part
  LEFT OUTER JOIN Product_Structure
    ON psparcomp.ps_par = Product_Structure.pt_part
  LEFT OUTER JOIN PaintSched ON MPA_Desc.MPAID = PaintSched.MPAID
WHERE Forecasts.schd_discr_qty > 0
GROUP BY psparcomp.ps_comp,
  MPA_Desc.Side,
  MPA_Desc.Color_Code,
  MPA_Desc.Description,
  ISNULL(Forecasts.schd_discr_qty, 0),
  Product_Structure.pt_promo,
  Forecasts.sod_nbr

这些是我的结果:

Results

我需要结果仅显示“ MPA-0856”和总计的订单金额。之所以要拉动多次,是因为从预测表中得出的零件代号是不同的零件代号,但是这些是涂漆的零件,用于多个零件代号。我在这里为我们的油漆部门创建报告,他们只需要查看需要油漆的总量,而不是零件号即可。我已经尝试了几种不同的联接方式,但是似乎没有任何效果。有人可以协助吗?

2 个答案:

答案 0 :(得分:3)

仅凭猜测:您的GROUP BY子句不应列出此项目:

pod 'VVJSONSchemaValidation', '1.5.0', :modular_headers => true
pod 'MyFramework', :git => 'https://myframework.git'

因为这是总和的一部分。

此外,从分组依据中删除并选择任何可能将结果分成不同行(例如颜色,侧面等)的项目

答案 1 :(得分:1)

使用窗口功能。 (https://www.sqlshack.com/use-window-functions-sql-server/

SELECT psparcomp.ps_comp,
  MPA_Desc.Side,
  MPA_Desc.Color_Code,
  MPA_Desc.Description,
  sum(ISNULL(Forecasts.schd_discr_qty, 0)) OVER (PARTITION BY .... ) AS [Order Amount],
  Product_Structure.pt_promo,
  Forecasts.sod_nbr,
  SUM(PaintSched.qty) OVER (PARTITION BY ..... ) AS schedamt
FROM MPA_Desc
  LEFT OUTER JOIN psparcomp ON MPA_Desc.MPA_Number = psparcomp.ps_comp
  LEFT OUTER JOIN Forecasts ON psparcomp.ps_par = Forecasts.sod_part
  LEFT OUTER JOIN Product_Structure
    ON psparcomp.ps_par = Product_Structure.pt_part
  LEFT OUTER JOIN PaintSched ON MPA_Desc.MPAID = PaintSched.MPAID
WHERE Forecasts.schd_discr_qty > 0
GROUP BY psparcomp.ps_comp,
  MPA_Desc.Side,
  MPA_Desc.Color_Code,
  MPA_Desc.Description,
  ISNULL(Forecasts.schd_discr_qty, 0),
  Product_Structure.pt_promo,
  Forecasts.sod_nbr