为什么我的聚合函数没有正确求和?

时间:2017-07-11 21:06:22

标签: sql-server tsql aggregate-functions

所以我在下面有这个代码,由于某种原因,返回的EstHrs是错误的。它适用于大多数行,但对于其他行,返回的值加倍,三倍。关闭的值似乎偏离了多个量(x2,x3等)。不确定我做错了什么

SELECT
   s.JobNo,
   ROUND(SUM(r.TotEstHrs), 3) AS EstHrs
FROM Scheduling s JOIN OrderRouting r ON s.JobNo = r.JobNo 
  AND s.WorkCntr = r.WorkCntr
WHERE s.WorkCntr = 'Cutting'
  AND r.OrderNo NOT IN ('44444', '77777')
GROUP BY s.JobNo;

表格结构:

计划:

JobNo(文字)

WorkCntr(文字)

OrderRouting:

JobNo(文字)

WorkCntr(文字)

TotEstHrs(数字)

1 个答案:

答案 0 :(得分:2)

最可能的原因是JobNo& Scheduling表中的WorkCntr。

编辑...

WITH 
    cte_DistinctScheduling AS (
        SELECT DISTINCT 
            s.JobNo
        FROM 
            dbo.Scheduling s
        WHERE 
            s.WorkCentr = 'Cutting'
        )
SELECT 
    ds.JobNo,
    ROUND(SUM(r.TotEstHrs), 3) AS EstHrs
FROM
    cte_DistinctScheduling ds
    JOIN dbo.OrderRouting r
        ON ds.JobNo = r.JobNo
WHERE 
    r.WorkCntr = 'Cutting'
    AND r.OrderNo NOT IN ('44444', '77777');