如果有一个表如下
年份 销售额
2001 1000
2002 1100
2003 1300
2004 1700
2005 2000
等等
如何输出如下记录
年份 增长百分比
2002 0.1 (1100-1000)/1000
2003 0.18 (1300-1100)/1100
2004 0.31 (1700-1300)/1700
等等,
感谢了。。。
use testdb2
go
--建表
IF NOT OBJECT_ID('[testSell]') IS NULL
DROP TABLE [testSell]
GO
create table testSell
(
Syear int,
SMoney Float
)
--插入数据
insert into testSell values(2001,1000);
insert into testSell values(2002,1100);
insert into testSell values(2003,1300);
insert into testSell values(2004,1700);
insert into testSell values(2005,2000);
select s.SYear as 年份,s.SMoney as 今年,t.SMoney as 去年,
(s.SMoney-t.SMoney)/t.SMoney as 增长率
From testSell s
inner join TestSell t on t.SYear=s.SYear-1
/*结果
年份 今年 去年 增长率
2002 1100 1000 0.1
2003 1300 1100 0.181818181818182
2004 1700 1300 0.307692307692308
2005 2000 1700 0.176470588235294
*/
/*
--建表
create table test
(
年份 int,
销售额 int
)
--插入数据
insert into Test values(2001,1000);
insert into Test values(2002,1100);
insert into Test values(2003,1300);
insert into Test values(2004,1700);
insert into Test values(2005,2000);
*/
--下面是游标(可以放在存储过程中)
declare @PreYear int, @PreYearCount int,@CurrYear int, @CurrentYearCount int;
declare cur cursor for select 年份,销售额 from test;
open cur;
fetch next from cur into @CurrYear,@CurrentYearCount;
while @@FETCH_STATUS=0
begin
set @PreYear=@CurrYear;
set @PreYearCount=@CurrentYearCount;
fetch next from cur into @CurrYear,@CurrentYearCount;
if @CurrYear!=@PreYear
select @CurrYear as 年份 ,cast((@CurrentYearCount-@PreYearCount)*1.0/@PreYearCount as decimal(18,2)) as 增长百分比;
end
close cur
DEALLOCATE cur
GO
--结果如下:
/*
年份 增长百分比
2002 0.10
(1 row(s) affected)
年份 增长百分比
2003 0.18
(1 row(s) affected)
年份 增长百分比
2004 0.31
(1 row(s) affected)
年份 增长百分比
2005 0.18
(1 row(s) affected)
*/
--你可以把上面的数据存入数据库中,要用时再取
select nian,(xiaoshou/(select xiaoshou from tb where nian=t.nian-1)-1) from tb t where nian>2001