0

在 sql 我有如下表数据

id      type     amount       
1      type1       2000    
2      type1       1000     
3      type2        500    
4      type3       3000    
5      type1       2000   
6      type2        500        
7      type3       5000    
8      type1       1000    

我想在 select 语句中获取数据,如下所示

id      type     amount      current   
1      type1       2000         2000                
2      type1       1000         1000                 
3      type2        500          500                 
4      type3       3000         3000                 
5      type1       2000         3000                  
6      type2       -500            0                 
7      type3       5000         2000
8      type1      -1000         4000 

依此类推,这意味着每种类型都必须具有基于数量类型的当前总量,并且不需要有 while 循环,因为执行需要很长时间

for eg:

in type 1

ID      Amount      current 
1      2000-add       2000                   
2      1000-sub       1000                  
3      2000-add       3000                   
4      1000-add       4000                   

怎么做

4

2 回答 2

0

自加入就足够了:

 select
    t1.id, t1.type, t1.amount, sum(t2.amount) as currenttotal
 from
  t t1 inner join t t2
 on t1.id >= t2.id and t1.type = t2.type
 group by
    t1.id, t1.type, t1.amount
 order by t1.id

在 sql fiddle 测试它

| ID |  TYPE | AMOUNT | CURRENTTOTAL |
--------------------------------------
|  1 | type1 |   2000 |         2000 |
|  2 | type1 |   1000 |         3000 |
|  3 | type2 |    500 |          500 |
|  4 | type3 |   3000 |         3000 |
|  5 | type1 |   2000 |         5000 |
|  6 | type2 |    500 |         1000 |
|  7 | type3 |   5000 |         8000 |
|  8 | type1 |  -1000 |         4000 |

解释

您不能使用窗口函数,因为您不会聚合具有相同值的所有行,而是聚合具有相同值的先前行。然后,您需要对同一个表进行非等值连接,您可以连接所有t1.id >= t2.id具有相同值 () 的 先前行 ( t1.type = t2.type)

于 2013-07-24T05:40:26.890 回答
0

我认为这个查询会起作用:

select id,type,amount,(select sum(amount) from mytable t1 where t1.type=t2.type and t1.id<=t2.id) currenttotal from mytable t2

于 2013-07-24T06:15:42.437 回答