0

我有以下表格 -

时间日志

ID
UserID
JobID
TimeTaken
JobPhase

工作材料

ID
StockID
JobID
UserID
Quantity

库存

ID
Name
CostPrice

以下查询返回重复行,因为分配给作业的库存项目不止一个,并且有多个阶段 (tl.Phase)。我的问题是,我怎样才能只返回 1 行的总和?通过按原样添加 SUM(),返回的值将是错误的。

SELECT 
    TimeTaken as 'HoursSold', s.CostPrice * mfj.Quantity as 'StockCost'
FROM 
    TimeLogs tl
LEFT JOIN 
    MaterialsForJob mfj ON mfj.JobID = tl.JobID AND mfj.UserID = tl.UserID
INNER JOIN 
    Stock s ON s.ID = mfj.StockID
WHERE 
    tl.UserID = 10000 AND
    tl.DateEntry BETWEEN DATEADD(wk, DATEDIFF(wk, 0, '11/07/2013'), 0) 
                     AND DATEADD(wk, DATEDIFF(wk, 0, '11/07/2013'), 6)

目前,上述查询返回 -

无效数据截图

但是,它应该显示 -

19570633502 - 30.00

希望这是有道理的。谢谢

4

1 回答 1

3

用 SUM 和 DISTINCT 试试这个查询。这应该会给你正确的结果:

SELECT t1.JobID AS JID, SUM(DISTINCT(TimeTaken)) as 'HoursSold', SUM(DISTINCT(s.CostPrice * mfj.Quantity)) as 'TotalStockCost'
FROM TimeLogs tl
LEFT JOIN MaterialsForJob mfj on mfj.JobID = tl.JobID and mfj.UserID = tl.UserID
INNER JOIN Stock s on s.ID = mfj.StockID
WHERE 
    tl.UserID = 10000 and 
    tl.DateEntry between dateadd(wk, datediff(wk,0,'11/07/2013'), 0) and
    dateadd(wk, datediff(wk,0,'11/07/2013'), 6)
GROUP BY JID
于 2013-11-08T16:49:25.080 回答