我正在试着计算下一个30天的销售额。
这是我的数据。
<表类>
日期
销售
tbody><<tr>2021-08-08 35 2021-08-08 14 2021-08-11 35 2021-09-09 22 2021-09-21 44 2021-10-16 46 2021-10-25 9 2021-10-25 1 2021-10-25 2 2021-10-25 6 2021-11-04 1 2021-11-07 1 表类>
这里有一种使用递归cte的方法。
with data
as (select start_dt,sales,row_number() over(order by start_dt) as rnk
from t1
)
,cte_data
as ( select d.start_dt,d.sales,d.rnk,d.start_dt as grp_dt
from data d
where rnk=1
union all
select d.start_dt,d.sales,d.rnk,case when datediff(day,d2.grp_dt,d.start_dt)>30 then
d.start_dt
else d2.grp_dt
end
from cte_data d2
join data d
on d.rnk=d2.rnk+1
)
select min(start_dt) start_range,max(start_dt) end_range,sum(sales) as sum_sales
from cte_data
group by grp_dt
+-------------+------------+-----------+
| start_range | end_range | sum_sales |
+-------------+------------+-----------+
| 2021-08-08 | 2021-08-11 | 84 |
| 2021-09-09 | 2021-09-21 | 66 |
| 2021-10-16 | 2021-11-07 | 66 |
+-------------+------------+-----------+
sql fiddle linkhttps://dbfiddle.uk/2LmQe5n5
详细说明一下。我们需要某种递归过程来做到这一点,因为下一行的结果取决于前一个输入日期,所以我怀疑我们可以使用窗口函数来做到这一点。
似乎您有一个重叠组的问题,您可以使用自连接和聚合如下:
SELECT T.date, T.sales,
SUM(D.sales) AS total_30d
FROM
test_table T JOIN test_table D
ON D.date BETWEEN T.date AND T.date + interval '30' day
GROUP BY T.date, T.sales
ORDER BY T.date, T.sales
查看演示
直接使用标量子查询:
select ext.*,
(
select sum(sales) from the_table
where "date" between ext.date and ext.date + 30
) as total_30d
from the_table as ext;
DB-fiddle演示。
<表类>日期 销售 和 tbody><<tr>2021-08-08 35 84 2021-08-08 14 84 2021-08-11 35 57 2021-09-09 22 66 2021-09-21 44 90 2021-10-16 46 66 2021-10-25 9 20 2021-10-25 1 20 2021-10-25 2 20 2021-10-25 6 20 2021-11-04 1 2 2021-11-07 1 1 表类>