这样的Sql语句怎么写(SQL Server)?
做项目用的数据库是SQL Server,在这过程中碰到这么一个问题:
数据库中主要有三列:
Year Month Je
2007 1 100
2007 2 200
2007 3 300
. . .
. . .
. . .
2008 1 1000
2008 2 2000
. . .
现在想得到各个月的累积数。
如现在是2007年6月,我想得到的是2007-1到2007-6月的累积。
需要的结果如下:
Year Month Je
2007 1 100
2007 2 300
2007 3 600
. . .
. . .
. . .
2008 1 1000
2008 2 3000
. . .
这样的Sql 语句应该怎样写,请各位大虾帮忙,一旦解决,立即给分。
[解决办法]
select year,month,sum(je) group by year,month
是这个意思吗?
注:楼主上面的和下面想要的结果好象是一模一样的,...
[解决办法]
create table test(
syear varchar(4),
smonth varchar(2),
je int
)
insert into test
select '2007 ', '1 ',100 union all
select '2007 ', '2 ',200 union all
select '2007 ', '3 ',300 union all
select '2007 ', '4 ',500 union all
select '2008 ', '1 ',1000 union all
select '2008 ', '2 ',2000
go
create view TestView as
select syear,smonth,(select sum(je) from test as b where a.syear=b.syear and b.smonth <=a.smonth) as je from test as a
go
select * from TestView
drop table test
drop view TestView
[解决办法]
create table tbl(
syear varchar(4),
smonth varchar(2),
je int
)
insert into tbl
select '2007 ', '1 ',100 union all
select '2007 ', '2 ',200 union all
select '2007 ', '3 ',300 union all
select '2007 ', '4 ',500 union all
select '2008 ', '1 ',1000 union all
select '2008 ', '2 ',2000
go
select syear, smonth,(select sum(je) from tbl where a.syear=syear and a.smonth> =smonth) from tbl a