Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Trailing Sum Query

I am looking to summarize date and need to find a way of doing a 3 day trailing sum, sum of the current date and the 2 previous days. I am using MariaDB, a MYSQL fork.

Here is a subset of the data;

select Date, Total from keywordSum limit 5;
+------------+--------+
| Date       | Total  |
+------------+--------+
| 2010-11-11 | 316815 |
| 2010-11-12 | 735305 |
| 2010-11-13 | 705116 |
| 2010-11-14 | 725020 |
| 2010-11-15 | 745378 |
+------------+--------+

I would like to end up with a result similar to this:

+------------+--------+-----------+
| Date       | Total  | 3DayTotal |
+------------+--------+-----------+
| 2010-11-11 | 316815 |    316815 |
| 2010-11-12 | 735305 |   1052120 |
| 2010-11-13 | 705116 |   1757236 |
| 2010-11-14 | 725020 |   2167441 |
| 2010-11-15 | 745378 |   2177514 |
+------------+--------+-----------+

It could even print NaN or leave it blank if the previous days don't exist. Any thoughts or suggestions would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One simple way is to join the table to itself. Make sure it is indexed on a combination of date and total.

select t1.date
     , t1.total
     , t1.total 
      +coalesce(t2.total,0)
      +coalesce(t3.total,0)
  from theTable t1
  left 
  join theTable t2 on t1.date = date_Add(t2.date,interval 1 day)
  left
  join theTable t3 on t1.date = date_Add(t3.date,interval 2 day)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...