计算 sql 中的种群突变

Calculating stock mutations in sql

我想计算出库 = 每天离开仓库的产品数量。 如果我 运行 这些查询,我可以看到 sql 以某种方式计算数量加倍,但我不明白为什么。谁能看到问题?我怎样才能避免这种情况?

SELECT readYesterday.ArticleCode,
       MAX(readToday.ArticleCode) AS ArticleCodeToday,
       readYesterday.ReportDate,
       SUM(ISNULL(readToday.TotalStock, 0)) AS TotalStockToday,
       SUM(readYesterday.TotalStock) AS TotalStockYesterday,
       SUM(readYesterday.TotalStock - ISNULL(readToday.TotalStock, 0)) AS Outbound
FROM ArticleReads readYesterday
LEFT JOIN ArticleReads readToday ON readToday.ArticleCode = readYesterday.ArticleCode
AND readToday.InboundDossier = readYesterday.InboundDossier
AND readToday.ReportDate = DATEADD(DAY, 1, readYesterday.ReportDate)
WHERE readYesterday.ArticleCode ='ART01234'
  AND readToday.ReportDate <> Convert(date, getdate())
  AND readYesterday.ReportDate = '2018-04-26'
GROUP BY readYesterday.ArticleCode,
         readYesterday.ReportDate
ORDER BY ReportDate ASC

SELECT *
FROM ArticleReads readYesterday
WHERE readYesterday.ArticleCode = 'ART01234'
  AND readYesterday.ReportDate = '2018-04-26'

SELECT *
FROM ArticleReads readYesterday WHERE readYesterday.ArticleCode = 'ART01234'
AND readYesterday.ReportDate = '2018-04-27'

Here you can see the results

连接昨天和今天的表时,必须确保连接在主键上。在你的例子中,你使用的是 articlecode、inbounddossieur 和 reportdate+1;但是,由于每行有 2 行,没有什么可以区分它们,因此连接将 return 4 行!您需要添加一个唯一指定每一行的连接条件 - 可能是位置代码?

and readToday.LocationCode=readYesterday.LocationCode