首页 新闻 会员 周边

请教SQL语句问题

0
悬赏园豆:10 [已解决问题] 解决于 2010-12-28 21:19

如果有一个表如下

年份           销售额

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

等等,

感谢了。。。

 

doo的主页 doo | 初学一级 | 园豆:8
提问于:2010-12-27 20:40
< >
分享
最佳答案
0

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
*/

 

收获园豆:10
邀月 | 高人七级 |园豆:25475 | 2010-12-28 09:48
用关联实现,很好的想法
eesee | 园豆:136 (初学一级) | 2011-01-09 12:56
其他回答(2)
0

/*
--建表
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)
*/

--你可以把上面的数据存入数据库中,要用时再取

 

artwl | 园豆:16736 (专家六级) | 2010-12-27 23:23
写得蛮好的。谢谢你费了很多时间。 不过我要的不是存储过程,而是SQL语句。。
支持(0) 反对(0) doo | 园豆:8 (初学一级) | 2010-12-28 07:44
0

select nian,(xiaoshou/(select xiaoshou from tb where nian=t.nian-1)-1)  from tb t where nian>2001

死白的man | 园豆:2135 (老鸟四级) | 2010-12-28 09:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册