如何在单个查询中获取一天的总和和最近三天的总和? [英] How to get sum of one day and sum of last three days in single query?
本文介绍了如何在单个查询中获取一天的总和和最近三天的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的统计表:
Suppose I have a statistical table like this:
date | stats
-------------
10/1 | 2
10/1 | 3
10/1 | 2
10/2 | 1
10/3 | 3
10/3 | 2
10/4 | 1
10/4 | 1
我想要的是三列:
- 日期
- 日期总和
- 日期前三天的总和
我知道我可以使用window函数来处理第二列,但是我不能同时处理第二和第三列。
I know I can use window function to handle the 2nd column, but I cannot handle 2nd and 3rd at the same time.
我应该怎么存档?
谢谢!
推荐答案
您可以使用聚合和窗口函数:
You can use aggregation and window functions:
select date, sum(stats) as day_stats,
sum(sum(stats)) over (order by date rows between 3 preceding and 1 preceding) as day_stats_3
from t
group by date
order by date;
这篇关于如何在单个查询中获取一天的总和和最近三天的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文