日期:2014-05-18  浏览次数:20521 次

SQL查询计算股票均价的一些疑问
各位SQL达人,请教有一个计算股票均价的问题,

1. 现有数据表:
class name date open high low close volume amount
TD Ag(T+D) 5/27/2011 8170 8285 7986 8220 2353550 19193200640
TD Ag(T+D) 5/26/2011 8101 8485 8101 8335 2161338 17893718016
TD Ag(T+D) 5/25/2011 7810 7985 7810 7970 1635332 12943652864
TD Ag(T+D) 5/24/2011 7590 7735 7544 7719 880242 6732090880
TD Ag(T+D) 5/23/2011 7699 7706 7530 7538 702958 5350213120
TD Ag(T+D) 5/20/2011 7665 7740 7545 7693 1415364 10828949504
TD Ag(T+D) 5/19/2011 7525 7797 7451 7673 2083480 15965707264

2.想计算出的结果是:
class name date MA5 MA10 MA20 MA30 MA60

其中 MA5计算方式是 5天连续收盘价的AVG, 同理MA10,MA20。指的是10天,20天的收盘价移动平均。
查询MA5 T-SQL的语句是:


select b.class,b.name,b.date,avg(b.clo_2) as MA5
From (
select t1.*,t2.clo as CLO_2 from data_RN t1 inner join data_RN t2 on t1.name= t2.name and t2.rn<=t1.rn and t2.rn>=t1.rn-4
)b
group by b.class,b.name,b.rn,b.date
Order by name,date desc

3.现在的问题是,如何讲MA5到MA60一次性的计算出来呢? 如果不用T-SQL直接计算,这种情况是不是应该使用SSIS?Thanks in advance,



------解决方案--------------------
SQL code
--如果上市公司名叫name,要从一个总表中得到各股票的均价,则
select name,
(select avg(close) from(select top 5 close from tb where name=a.name order by date desc)t) as MA5,
(select avg(close) from(select top 10 close from tb where name=a.name order by date desc)t) as MA10,
(select avg(close) from(select top 20 close from tb where name=a.name order by date desc)t) as MA20,
(select avg(close) from(select top 30 close from tb where name=a.name order by date desc)t) as MA30,
(select avg(close) from(select top 60 close from tb where name=a.name order by date desc)t) as MA60
from tb a

------解决方案--------------------
探讨
试了一下,结果变成MA5以5为周期计算均值了,MA10以10为周期计算了。。。


MA5
stock 000300 2005-04-08 NULL
stock 000300 2005-04-11 NULL
stock 000300 2005-04-12 NULL
stock 000300 2005-04-13 NULL
stock 000300 2005-04-14 993.……