SQL返回重复项

时间:2013-11-08 16:45:59

标签: sql sql-server sql-server-2008

我有以下表格 -

TimeLogs

ID
UserID
JobID
TimeTaken
JobPhase

MaterialsForJob

ID
StockID
JobID
UserID
Quantity

库存

ID
Name
CostPrice

以下查询返回重复行,因为有多个库存项目分配给作业和多个阶段(tl.Phase)。我的问题是,如何只用sum来返回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)

目前,上述查询返回 -

Screenshot of invalid data

然而,它应该显示 -

19570633502 - 30.00

希望这是有道理的。感谢

1 个答案:

答案 0 :(得分: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