6

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

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

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

4 回答 4

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 
于 2012-09-27T12:11:34.640 回答
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 
于 2012-09-27T12:08:50.440 回答
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
于 2012-09-27T12:34:47.267 回答
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
于 2020-02-12T04:58:10.783 回答