从SQL上不规则日期集滚动3个月总和和行数
是否有可能获得每个id的滚动3个月总和(值) 数据:从SQL上不规则日期集滚动3个月总和和行数,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,是否有可能获得每个id的滚动3个月总和(值) 数据: +--------------------+---------------+----------------+---------------+ | tiq_transaction_id | id | date | value | +--------------------+---------------+----------------+---------------+ |
+--------------------+---------------+----------------+---------------+
| tiq_transaction_id | id | date | value |
+--------------------+---------------+----------------+---------------+
| 23980806 | a | 2018-05-15 | 73614336.7168 |
| 24957628 | a | 2018-09-28 | 47859499.2648 |
| 25403113 | a | 2018-11-23 | 40708340.1377 |
| 25771232 | a | 2019-01-07 | 15180519.2423 |
| 23455679 | b | 2018-02-27 | 21032280.0296 |
| 24456317 | b | 2018-07-25 | 8081544.0407 |
| 22963119 | c | 2017-12-01 | 7570269.5457 |
| 22962927 | c | 2017-12-04 | 8632491.8602 |
| 22962741 | c | 2017-12-05 | 7029459.0614 |
| 22982978 | c | 2017-12-06 | 5147303.2 |
| 22982751 | c | 2017-12-07 | 7667280.7413 |
| 22982520 | c | 2017-12-08 | 10090265.727 |
| 23007107 | c | 2017-12-11 | 4930930.2813 |
+--------------------+---------------+----------------+---------------+
这是你的问题。(适用于MS SQL Server)
dateadd(月,日期差(月,0,[date]),0)
请尝试在标准SQL中使用窗口函数和间隔定义:
select id,
date,
value,
sum(value) over (partition by id
order by date
range between '3 month' preceding and current row) as running_sum
from the_table
order by id, date;
(使用Postgres)您迄今为止尝试了什么?还有期望的输出?你试过使用“订单依据”和“分组依据”吗。。。但我一直在思考如何根据看起来随机的日期获得滚动3个月的总和(如移动总和)。您使用的是哪种产品?“SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加一个“
postgresql
”、oracle
、sqlserver
、db2
”,…谢谢,您介意详细说明一下定义3个月间隔的内容吗?@kwknpui:这是之前的“3个月”之间的“”部分,但我认为SQLServer不支持这一点。
select id,
date,
value,
sum(value) over (partition by id
order by date
range between '3 month' preceding and current row) as running_sum
from the_table
order by id, date;