[英]Rolling Sum (4 Months)
I have been struggeling with building a query in access that calculates a "rolling 4 months" of sales data.我一直在努力在访问中构建一个查询来计算“连续 4 个月”的销售数据。 I have been experimenting with DSUM, but I only seem to be able to get the subtotal or running total for a specific group (not a moving total).
我一直在试验 DSUM,但我似乎只能获得特定组的小计或运行总计(而不是移动总计)。 I have tried to illustrate what I am trying to do below.
我试图在下面说明我正在尝试做的事情。
Date Product Value Rolling_4_Month_Sum
January A 100 100
February A 200 300
March A 300 600
April A 300 900
May A 200 1000
June A 400 1200
July A 500 1400
August A 700 1800
Is it possible to make a running total for 4 rows/months only?是否可以仅对 4 行/月进行累计?
SELECT
a.Date,
a.Product,
a.Value,
SUM(b.value)
FROM
Table a
INNER JOIN Table b ON a.Product=b.Product
AND b.Date <= a.Date
AND b.Date >= DateAdd("q",1, a.Date)
GROUP BY
a.Date, a.Product
This should work in my opinion.这在我看来应该有效。
Table a is your "single month" row date.表 a 是您的“单月”行日期。 Table b is self join to retrieve the last 4 predecessing months.
表 b 是自联接以检索过去 4 个月。 It is done by adding
b.Date >= DateAdd("q",1, a.Date)
as self-join criteria.它是通过添加
b.Date >= DateAdd("q",1, a.Date)
作为自b.Date >= DateAdd("q",1, a.Date)
条件来完成的。
Here is a nice example of how these kinds of things work.这是一个很好的例子,说明这些事情是如何工作的。
Data:数据:
OrderDetailID OrderID ProductID Price
1 1234 1 $5.00
2 1234 2 ($2.00)
3 1234 3 $4.00
4 1235 1 $5.00
5 1235 3 $4.00
6 1235 5 $12.00
7 1235 2 ($2.00)
SQL:查询语句:
SELECT OD.OrderDetailID, OD.OrderID, OD.ProductID, OD.Price, (SELECT Sum(Price) FROM tblOrderDetails
WHERE OrderDetailID <= OD.OrderDetailID) AS RunningSum
FROM tblOrderDetails AS OD;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.