sql – 按表中的分组记录运行总计

我有这样的表(Oracle,10)
Account     Bookdate     Amount
      1     20080101        100
      1     20080102        101
      2     20080102        200
      1     20080103       -200
...

我需要的是按帐户asc和Bookdate asc按帐户顺序分组的新表格,其中包含一个正在运行的总字段,如下所示:

Account     Bookdate     Amount     Running_total
      1     20080101        100               100
      1     20080102        101               201
      1     20080103       -200                 1
      2     20080102        200               200
...

一个简单的方法吗?

提前致谢.

解决方法

你真的需要额外的桌子吗?

您可以使用简单的查询获得所需的数据,如果您希望它看起来像表格,您可以将其显然创建为视图.

这将为您提供您正在寻找的数据:

select 
    account,bookdate,amount,sum(amount) over (partition by account order by bookdate) running_total
from t
/

这将创建一个视图,向您显示数据,就好像它是一个表:

create or replace view t2
as
select 
    account,sum(amount) over (partition by account order by bookdate) running_total 
from t
/

如果你真的需要这张桌子,你的意思是你需要不断更新吗?还是只有一次?显然,如果它是一个一个,你可以使用上面的查询“创建表作为选择”.

我使用的测试数据是:

create table t(account number,bookdate date,amount number);

insert into t(account,amount) values (1,to_date('20080101','yyyymmdd'),100);

insert into t(account,to_date('20080102',101);

insert into t(account,to_date('20080103',-200);

insert into t(account,amount) values (2,200);

commit;

编辑:

忘了加;你指定你想要对表进行排序 – 这实际上没有意义,并且让我认为你真的意味着你想要查询/视图 – 排序是你执行的查询的结果,而不是那些在表(忽略索引组织表等).

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...