想要這樣的匯總有好方法嗎?

Stone444 2004-11-05 10:04:08
根據下表:
日期 a類金額 b類金額 c類金額
2004/05/01 100 150 220
2004/05/02 120 150 120
2004/05/03 160 120 300
2004/05/04 200 300 900
2004/05/05 100 450 100
... ... ... ...
匯總結果要求如下:
日期 a類金額 b類金額 c類金額
2004/05/01 100 150 220
2004/05/02 220 300 340
2004/05/03 380 570 640
2004/05/04 580 870 1540
2004/05/05 680 1320 1640
誰有好的方法呢?各位DX幫助一下,感激不盡!
...全文
77 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
光原 2004-11-06
  • 打赏
  • 举报
回复
游标的方法,参考
declare errors scroll cursor for
select id,value from tb
open errors
if exists (select name from sysobjects where name = 'table_rate_yzg_p3') drop table table_rate_yzg_p3
create table table_rate_yzg_p3
(
id varchar(10),
value int,
)
go
declare @i int,@row int,@id char(10),@value int,@zong int
set @i=0
set @zong=0
label:
set @i=@i+1
fetch next from errors into @id,@value
begin
set @zong = @zong + @value
insert into table_rate_yzg_p3 select @id,@zong
end
if @i<@@cursor_rows
goto label
select * from table_rate_yzg_p3
if exists (select name from sysobjects where name = 'table_rate_yzg_p3') drop table table_rate_yzg_p3
close errors
deallocate errors
Andy__Huang 2004-11-05
  • 打赏
  • 举报
回复

create table tb(日期 datetime, a類金額 numeric(10), b類金額 numeric(10), c類金額 numeric(10))
Insert into tb
select '2004/05/01','100','150','220'
union all select '2004/05/02','120','150','120'
union all select '2004/05/03','160','120','300'
union all select '2004/05/04','200','300','900'
union all select '2004/05/05','100','450','100'


select 日期=convert(varchar(10),a.日期,120)
,a類金額 =(select sum(a類金額) from tb where 日期<=a.日期)
, b類金額 =(select sum(b類金額) from tb where 日期<=a.日期)
, c類金額 =(select sum(c類金額) from tb where 日期<=a.日期)
from tb a

--結果
日期 a類金額 b類金額 c類金額
-------------------------------------------
2004-05-01 100 150 220
2004-05-02 220 300 340
2004-05-03 380 420 640
2004-05-04 580 720 1540
2004-05-05 680 1170 1640
zjcxc 元老 2004-11-05
  • 打赏
  • 举报
回复
select 日期
,a類金額=(select sum(a類金額) from 表 where 日期<=a.日期)
,b類金額=(select sum(b類金額) from 表 where 日期<=a.日期)
,c類金額=(select sum(c類金額) from 表 where 日期<=a.日期)
from 表 a

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧