2012-09-17 35 views
1

我有一个问题构建一个聚合函数。这里是我的问题:构建SUM基于日常记录

我有这样

id action day   isSum difference 
1 ping 2012-01-01 1  500   (this is the sum of the differences from last year) 
2 ping 2012-01-01 0  -2 
3 ping 2012-01-02 0  1 
4 ping 2012-01-03 0  -4 
5 ping 2012-01-04 0  -2 
6 ping 2012-01-05 0  3 
7 ping 2012-01-06 0  2 
8 ping 2012-01-01 1  0   (this is the sum of the differences from last year, now for pong) 
9 pong 2012-01-01 0  -5 
10 pong 2012-01-02 0  2 
11 pong 2012-01-03 0  -2 
12 pong 2012-01-04 0  -8 
13 pong 2012-01-05 0  3 
14 pong 2012-01-06 0  4 

我现在需要选择的动作,一天01-01以来每天汇总的差异,因此,我的结果看起来像这样

action day  total  
ping 2012-01-01 498 
ping 2012-01-02 499 
ping 2012-01-03 495 
ping 2012-01-04 493 
ping 2012-01-05 496 
ping 2012-01-06 498 
pong 2012-01-01 - 5 
pong 2012-01-02 - 3 
pong 2012-01-03 - 5 
pong 2012-01-04 -13 
pong 2012-01-05 -10 
pong 2012-01-06 - 6 

我该怎么做?

那里有很多数据集(〜100万),所以查询需要相当便宜。我不知道如何根据行动栏来获得日常记录的总和。

回答

2

您需要使用SUBQUERY才能获得总字段。

select action, day, 
(select sum(difference) from x 
    where action = t2.action and day <= t2.day 
    group by action) as total 
from x t2 group by action ,day 

看到它在SQLFIDDLE

+0

很大,这就是它!谢谢! – ximarin