gpt4 book ai didi

mysql - 滚动 12 个月的数据 Sum 运算

转载 作者:行者123 更新时间:2023-11-29 05:48:35 25 4
gpt4 key购买 nike

我见过滚动 12 的平均值和计数,但不是总和。

我有这样一张 table

ID | Profile_ID | EntryLocation | EntryMonth   |    Usage 
-----------------------------------------------------------
1 | 1 | 11 | 2019-06-01 | 60.00
2 | 1 | 12 | 2019-05-01 | 40.00
3 | 1 | 11 | 2019-05-01 | 30.00
4 | 2 | 11 | 2019-06-01 | 100.00
5 | 1 | 12 | 2019-06-01 | 74.00
6 | 2 | 12 | 2019-06-01 | 456.00
7 | 2 | 11 | 2019-05-01 | 33.00
8 | 1 | 11 | 2019-07-01 | 200.00
9 | 1 | 11 | 2018-06-01 | 100.00

我想做的是总结前几个月的使用情况,分组为 Profile_IDEntryLocationEntryMonth(其中组成一个聚簇主键(即三者的组合是唯一的)。

所以我正在寻找的结果如下:

ID | Profile_ID | EntryLocation | EntryMonth   |    Rolling12Usage 
-----------------------------------------------------------
1 | 1 | 11 | 2018-06-01 | 100.00
2 | 1 | 11 | 2019-05-01 | 130.00 --> (100 + 30)
3 | 1 | 11 | 2019-06-01 | 90.00 -->(30 + 60 (note the 100 fell off))
4 | 1 | 11 | 2019-07-01 | 290.00 -->(90 + 200)
5 | 1 | 12 | 2019-05-01 | 40.00
6 | 1 | 12 | 2019-06-01 | 114.00 -->(40 + 74)
7 | 2 | 11 | 2019-05-01 | 33.00
8 | 2 | 11 | 2019-06-01 | 133.00 -->(33 + 100)
9 | 2 | 12 | 2019-06-01 | 456.00

我试过分组

select x.Profile_ID, x.EntryLocation, x.EntryMonth, sum(Usage) as [SumUsage],
(sum(sum(Usage)) over (order by x.EntryMonth rows between 11 preceding and current row)
) as Sum_12month
from my_table_with_values x
group by x.EntryMonth, x.Profile_ID, x.EntryLocation
order by x.EntryMonth

但无法正确排序。有什么想法/帮助吗?

如果你想添加解决方案而不假设这些值的集群主键(我敢打赌这种情况可能比我的情况更常见/更常见)。

最佳答案

这是您要找的吗?

SELECT x.Profile_ID, 
x.EntryLocation,
x.Entry_Month,
SUM(x2.Usage)
FROM my_table_with_values x
LEFT
JOIN my_table_with_values x2
ON x.Profile_id = x2.Profile_id
AND x.Entry_Location x2.Entry_Location
AND x2.Entry_Month BETWEEN DATEADD(month, -11, x.entrymonth)
And x.entrymonth
GROUP
BY x.Profile_ID,
x.EntryLocation,
x.Entry_Month

关于mysql - 滚动 12 个月的数据 Sum 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57083518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com