假设我有一个这样的统计表:
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
我想要的是三列:
我知道我可以使用窗口函数来处理第二列,但我无法同时处理第二列和第三列。
我该怎么做才能存档?
谢谢!
答案 0 :(得分:5)
您可以使用聚合和窗口函数:
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;
答案 1 :(得分:1)
您可以使用相关查询:
SELECT s.date,sum(s.stats) as today_sum,
(SELECT sum(t.stats) FROM YourTable t
where t.date between s.date - 2 and s.date) as sum_3days
FROM YourTable s
GROUP BY s.date