加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

SQL中处理数据—计算跌涨幅度两种方法

(2012-06-25 16:21:56)
标签:

sql

游标

数据处理

连接

分类: SQL

    很多时候难免会在SQL中处理一些数据,计算一些数据,因此可能需要用到一些基本方法进行处理,本文中以计算一列数据的跌涨幅为例,分别采用链接查询和游标对跌涨幅进行计算。

  1. 通过连接查询计算跌涨幅

    如果表中并没有自动增加或者连续性的数据,类似编号的数据,如:1,2,3,4...... 需要构建一列数据为类似的相同间隔的连续性数据。然后通过连接查询计算其跌涨幅。(其中:向一列查插入连续性数据,我只知道用游标实现)

use DB
alter table table add ID int null

go

-----利用游标向一列数据中加入连续值
declare cursor1 cursor dynamic
for select UV from table open  cursor1
declare @a int,@b int,@c int
fetch next from cursor1 into @a
set @c=1
set @b=0
while @@FETCH_STATUS=0
begin
 if @a<>0
  set @b=@b+@c
 else
  set @b=@b+1
 update table set ID=@b  where current of cursor1
 fetch next from cursor1 into @a
end
close cursor1
deallocate cursor1
go

select t1.UV,t1.ma10,cast(t2.UV/t1.UV-1 as decimal(10,4)) as pcf
from  tablename t1 left join liuxue16803 t2 on t1.ma10= t2.ma10+1

 

    2.  通过游标方式计算跌涨幅

  通过游标实现其计算跌涨幅,但是不推荐使用游标,游标的效率较低,尤其在大数据下,数据量一大处理数据的时间就非常大长。因此应该首选其他效率较高的方式。

use stu2
set nocount on
declare P_cursor cursor dynamic---建立游标P_cursor
for select UV from tablename declare @uv float,@uv_lag float-----必须定义为float型
open P_cursor---打开游标
fetch next from P_cursor into @uv------游标指向

fetch next from P_cursor into @uv_lag
while @@FETCH_STATUS=0
begin
 update dbo.tablename 
 set ma10=cast((@uv_lag-@uv)/@uv as decimal(10,4)) where current of P_cursor
 fetch next from P_cursor into @uv------同上面的游标指向
 fetch next from P_cursor into @uv_lag
end
close P_cursor
deallocate P_cursor
go
select date1,UV,ma10,Pcf,ID from tablename

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有