无法使用group by获得正确的SUM

时间:2018-06-12 11:59:12

标签: sql sql-server sql-server-2014

我一直试图获得TotalChargeTotalCostTotal Estimated hours

虽然我的脚本中没有错误,但有些错误我无法获得上述列的总数。

我的脚本如下:

SELECT
  l.LaborName,
  l.EstimatedHours,
  l.TotalCost,
  l.TotalCharge,
  w.CurrencySymbol,
  SUM(l.TotalCost) AS totalCost,
  SUM(l.TotalCharge) AS totalCharge,
  SUM(l.EstimatedHours) AS totalHours
FROM WOLabor l
INNER JOIN WO w
  ON l.WOPK = w.WOPK
WHERE l.WOPK = 10100
AND RecordType = 1
GROUP BY l.LaborName,
         l.EstimatedHours,
         l.TotalCost,
         l.TotalCharge,
         w.CurrencySymbol

这是我的输出:

enter image description here

我的预期输出是 enter image description here

3 个答案:

答案 0 :(得分:3)

您按列进行分组,只需要总和。  从GROUP BY

中删除它们
 SELECT
      l.LaborName,
      w.CurrencySymbol,
      SUM(l.TotalCost) AS totalCost,
      SUM(l.TotalCharge) AS totalCharge,
      SUM(l.EstimatedHours) AS totalHours
    FROM WOLabor l
    INNER JOIN WO w
      ON l.WOPK = w.WOPK
    WHERE l.WOPK = 10100
    AND RecordType = 1
    GROUP BY l.LaborName,
             w.CurrencySymbol

答案 1 :(得分:2)

您似乎想要窗口功能:

overall sum

我怀疑您需要partition,如果是,请删除SELECT . . . SUM(l.TotalCost) over () AS totalCost, SUM(l.TotalCharge) over () AS totalCharge, SUM(l.EstimatedHours) over () AS totalHours FROM WOLabor l INNER JOIN WO w ON l.WOPK = w.WOPK WHERE l.WOPK = 10100 AND RecordType = 1; 子句

{{1}}

答案 2 :(得分:0)

由于你没有接受任何给定的答案,我猜你正在寻找"整个数据"总和,因此您只需从

中删除选择和分组中的LaborNameEstimatedHours即可
SELECT
  l.LaborName,
  CONVERT(NVARCHAR, l.EstimatedHours) [EstimatedHours],
  CONVERT(NVARCHAR, l.TotalCost) TotalCost,
  CONVERT(NVARCHAR, l.TotalCharge) TotalCharge
FROM WOLabor l
INNER JOIN WO w
  ON l.WOPK = w.WOPK
WHERE l.WOPK = 10100
AND RecordType = 1

UNION ALL

SELECT
  'Estimated Labor Totals',
  SUM(l.EstimatedHours) AS totalHours,
  --CONCAT(W.CURRENCYSYMBOL, ' ', CONVERT(NVARCHAR, SUM(L.TOTALCOST))),
  --CONCAT(W.CURRENCYSYMBOL, ' ', CONVERT(NVARCHAR, SUM(L.TOTALCHARGE))) 
  W.CURRENCYSYMBOL + ' ' + CONVERT(NVARCHAR, SUM(L.TOTALCOST)),
  W.CURRENCYSYMBOL + ' ' + CONVERT(NVARCHAR, SUM(L.TOTALCHARGE))     
FROM WOLabor l
INNER JOIN WO w
  ON l.WOPK = w.WOPK
WHERE l.WOPK = 10100
AND RecordType = 1
GROUP BY W.CURRENCYSYMBOL

sql fiddle here

输出:

LaborName               EstimatedHours  TotalCost   TotalCharge
Barnes, Ashley          1               9           9.9
Chelsea, Smith          1               9           30
Estimated Labor Totals  2               Mex$ 18     Mex$ 39.9