加入第二个表时总和不正确

时间:2012-09-27 11:55:27

标签: sql sql-server-2008 join sum

这是我第一次请求你的帮助,

实际上我必须创建一个查询,并为它做了一个类似的例子。我有两张桌子,

Report (ReportID, Date, headCount)
Production(ProdID, ReportID, Quantity)

我的问题是使用此查询,我得到了错误的结果,

SELECT    
    Report.date, 
    SUM(Report.HeadCount) AS SumHeadCount, 
    SUM(Production.Quantity) AS SumQuantity
FROM         
    Report 
INNER JOIN
    Production ON Report.ReportID = Production.ReportID
GROUP BY
    Date
ORDER BY
    Date

我猜有些行不止一次,请你帮个忙吗?

修改

如果我运行查询以获得按天分组的人数总和,我得到:

  date        Headcount
7/2/2012    1843
7/3/2012    1802
7/4/2012    1858
7/5/2012    1904

对于生产数量,我得到:

2012-07-02  8362
2012-07-03  8042
2012-07-04  8272
2012-07-05  9227

但是当我结合两个查询时,我得到的是假的,我预计7月2日8362对1843年的数量,但我得到:

 day      TotalHeadcount    totalQty
7/2/2012    6021    8362
7/3/2012    7193    8042
7/4/2012    6988    8272
7/5/2012    7197    9227

4 个答案:

答案 0 :(得分:3)

避免这种情况的一种方法(受RDBMS支持)将是

WITH R
     AS (SELECT *,
                Sum(HeadCount) OVER (PARTITION BY date) AS SumHeadCount
         FROM   Report)
SELECT R.date,
       SumHeadCount,
       Sum(P.Quantity) AS SumQuantity
FROM   R
       JOIN Production P
         ON R.ReportID = P.ReportID
GROUP  BY R.date, SumHeadCount
ORDER  BY R.date 

答案 1 :(得分:2)

这可能会有所帮助

SELECT Report.ReportDate,
       Sum(Report.HeadCount) AS SumHeadCount,
       ProductionSummary.SumQuantity
FROM   Report
       INNER JOIN (SELECT ReportID,
                          Sum(Production.Quantity) AS SumQuantity
                   FROM   Production
                   GROUP  BY ReportID) AS ProductionSummary
         ON Report.ReportID = ProductionSummary.ReportID
GROUP  BY ReportDate
ORDER  BY ReportDate 

答案 2 :(得分:1)

使用以下

对每个日期进行分组记录
SELECT ReportSummary.ReportDate, SUM(ReportSummary.SumHeadCount) AS SumHeadCount, SUM(ProductionSummary.SumQuantity) AS SumQuantity
FROM
(
  SELECT Report.ReportDate, SUM(Report.HeadCount) AS SumHeadCount
  FROM Report 
  GROUP BY Report.ReportDate
) AS ReportSummary
INNER JOIN
(
  SELECT Report.ReportDate, Sum(Production.Quantity) AS SumQuantity
  FROM Production
  INNER JOIN Report 
  ON Report.ReportID = Production.ReportID
  GROUP BY Report.ReportDate
) AS ProductionSummary
ON ReportSummary.ReportDate = ProductionSummary.ReportDate
GROUP BY ReportSummary.ReportDate
ORDER BY ReportSummary.ReportDate

答案 3 :(得分:0)

我们有同样的问题,但我解决了。试试这个。

SELECT tbl_report.SumHeadCount, tbl_report.date, tbl_production.SumQuantity
FROM
 ( select date, 
    SUM(HeadCount) AS SumHeadCount FROM  Report GROUP by date)as tbl_report
JOIN
 ( select SUM(Quantity) AS SumQuantity, date FROM  Production GROUP by date)as tbl_production
WHERE tbl_report.date = tbl_production.date