我想基于两个日期更新我的查询表,我尝试了以下代码,但它不起作用
UPDATE [Stock Report] INNER JOIN Report ON [Stock Report].ItemID = Report.ItemID SET [Stock Report].Amount = SUM(Report.Amount) WHERE [Date Product Was Made] BETWEEN @AA AND @BB
我的两个查询表是报告和库存报告
报告表
ItemID| Item |Date Product Was Made|Amount|ProductID|Product Name
10 Flour 11/17/2015 100 54 Saltbread
11 Bran Flakes 11/17/2015 100 54 Saltbread
10 Flour 11/17/2015 100 54 Saltbread
11 Bran Flakes 11/17/2015 100 54 Saltbread
我希望在股票报告表中看到什么
ItemID| Item | Start Date | End Date |Amount
10 Flour 11/16/2015 11/25/2015 200
11 Bran Flakes 11/16/2015 11/25/2015 200
日期可以是任意两个随机日期,但表格应根据日期范围之间使用的金额生成总计。 wht]将成为完成此过程的SQL代码
答案 0 :(得分:0)
您使用mysql,sql-server和ms-access标记。
但每个案例的答案都不同。
这里是SQLServer解决方案:
WITH SumAmount AS (
SELECT
ItemId
,SUM(Report.amount) as sum_amount
FROM
Report
GROUP BY
ItemId
)
UPDATE SR
SET
amount = SA.sum_amount
FROM
[Stock Report] SR
JOIN SumAmount SA ON SR.ItemID = SA.ItemID
WHERE
[Date Product Was Made] BETWEEN @AA AND @BB
提供MS Access查询(我不熟练使用MSACCESS,http://www.fmsinc.com/microsoftaccess/query/snytax/update-query.html):
UPDATE [Stock Report]
JOIN (
SELECT
ItemId
,SUM(Report.amount) as sum_amount
FROM
Report
GROUP BY
ItemId
) SA ON [Stock Report].ItemID = SA.ItemID
SET
[Stock Report].amount = SA.sum_amount
WHERE
[Date Product Was Made] BETWEEN @AA AND @BB
答案 1 :(得分:0)
正如EuphoriaGrogi所说,你非常接近。
SELECT ItemID, Item, @AA AS StartDate, @BB AS EndDate, SUM(Amount) AS TotalAmount
FROM (YourReportTableQueryWith@AAAnd@BBParametersHere) AS SubQuery
GROUP BY SubQuery.ItemID,SubQuery.Item
有关GROUP BY的更多信息,请访问:http://www.w3schools.com/sql/sql_groupby.asp