的过去12个月中累计总和
问题描述:
我试图做的最后一个累积和12个月如此,例如在201702它应该显示的201603总和201702.的过去12个月中累计总和
现在我有以下查询:
select date,
product,
sum(sales) over (partition by product order by date) as cumulative
FROM sales
的数据是这样的:
Date \t Product \t Sales \t Sales Acum
201601 \t 1 \t 7648 \t 7648
201602 \t 1 \t 5538 \t 13186
201603 \t 1 \t 7659 \t 20845
201604 \t 1 \t 6943 \t 27788
201605 \t 1 \t 7604 \t 35392
201606 \t 1 \t 4398 \t 39790
201607 \t 1 \t 3261 \t 43051
201608 \t 1 \t 3040 \t 46091
201609 \t 1 \t 5637 \t 51728
201610 \t 1 \t 5520 \t 57248
201611 \t 1 \t 8554 \t 65802
201612 \t 1 \t 4794 \t 70596
201701 \t 1 \t 6704 \t 69652
201702 \t 1 \t 2234 \t 66348
201703 \t 1 \t 4093 \t 62782
201704 \t 1 \t 4171 \t 60010
201705 \t 1 \t 6741 \t 59147
201706 \t 1 \t 2902 \t 57651
201601 \t 2 \t 582 \t 582
201602 \t 2 \t 2393 \t 100416
201603 \t 2 \t 4614 \t 105030
201604 \t 2 \t 2611 \t 107641
201605 \t 2 \t 6891 \t 114532
201606 \t 2 \t 4409 \t 118941
201607 \t 2 \t 5454 \t 124395
201608 \t 2 \t 7927 \t 132322
201609 \t 2 \t 6797 \t 139119
201610 \t 2 \t 6740 \t 145859
201611 \t 2 \t 8077 \t 153936
201612 \t 2 \t 5143 \t 159079
201701 \t 2 \t 6383 \t 67439
201702 \t 2 \t 1593 \t 66639
201703 \t 2 \t 5352 \t 67377
201704 \t 2 \t 4065 \t 68831
201705 \t 2 \t 7434 \t 69374
201706 \t 2 \t 2332 \t 67297
答
如果您想在上一年获取有关仅销售的信息,应该存在WHERE
条款中的适当条件。 对于Oracle,您可以使用下面的查询:
SELECT date,
product,
sum(sales) over (partition by product order by date) as cumulative
FROM sales
WHERE date >= add_months(sysdate, -12)
答
假设没有丢失一个月,你想总销售额的每个产品,您可以使用下面的查询 -
SELECT "Date"
, "Product"
, "Sales"
, SUM("Sales") OVER (PARTITION BY "Product" ORDER BY "Date" ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) AS Cumulative
FROM Sales;
可爱。那么问题是什么? –
您正在使用哪个[DBMS](https://en.wikipedia.org/wiki/DBMS)? Postgres的?甲骨文? –
请** [编辑] **您的问题,并根据该数据添加一些示例数据和预期输出。 [**格式文本**](http://stackoverflow.com/help/formatting)请,[**无截屏**](http://meta.stackoverflow.com/questions/285551/why-may -i-不上传图像-的代码上那么当灰化-A-问题/ 285557#285557)。 ** [编辑] **你的问题 - 做**不**的邮递区号或在注释中的附加信息。 –