表中数据累加的问题

今天一同事问我怎么用一条sql语句实现如下功能:

ID AMOUNT

—————–

1 3

2 5

3 6

4 8

要得到这样的结果:

ID AMOUNT TOTAL

———————–

1 3 3

2 5 8

3 6 14

4 8 22

这个问题是很常见也是很简单的问题,有两种解决方法:

1.用 oracle 的分析函数:

SELECT ID,AMOUNT,SUM(AMOUNT) OVER(ORDER BY ID) TOTAL FROM TABLE;

结果如下:

ID AMOUNT TOTAL

———————–

1 3 3

2 5 8

3 6 14

4 8 22

2.用JOIN+GROUP来实现:

我们这样分析:

当ID=1时,列出<=1的所有AMOUNT

当ID=2时,列出<=2的所有AMOUNT

当ID=3时,列出<=3的所有AMOUNT

同理,其他也一样

然后根据ID进行GROUP BY汇总即可得到所要的结果,那如何实现上面所说的列出所有AMOUNT呢?我们可以通过JOIN的不等连接来实现:

SQL> select t1.id id1,t1.amount total1,t2.id id2,t2.amount total2 from test t1 join test t2 on t1.id
>= t2.id;

ID1 TOTAL1 ID2 TOTAL2
———- ———- ———- ———-
4 8 4 8
4 8 3 6
4 8 2 5
4 8 1 3
3 6 3 6
3 6 2 5
3 6 1 3
2 5 2 5
2 5 1 3
1 3 1 3

看看,这就将所有的列出来了,然后根据ID1进行分组汇总就得到我们所要的:

SQL> select t1.id id1,sum(t2.amount) total from test t1 join test t2 on t1.id >= t2.id group by t1.i
d order by t1.id;

ID1 TOTAL
———- ———-
1 3
2 8
3 14
4 22

当然,这两种方法都有个前提,就是数据不能重复,如果有重复必须先将重复的汇总,当作一条纪录来计算。

  

No Comments

Be the first to comment on this entry.

Leave a comment

Name(required)
Mail (will not be published)(required)
Website

Fields in bold are required. Email addresses are never published or distributed.

Some HTML code is allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
URLs must be fully qualified (eg: http://www.dbifan.com),and all tags must be properly closed.

Line breaks and paragraphs are automatically converted.

Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.

    搜索本站

    站点日历

    4月 2007
    « 2   6 »
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30  

    订阅本站

    文章分类

    最新日志

    热点文章

    日志存档

    常用标签