2013-02-25 47 views
-1

我有這樣一個表:SQL Access 2010中計算股票每日峽

北京時間, 日期, Open_Price, Close_Price

包含行情的100S。我想添加另一個名爲Gap的計算列,即Open_price - 昨天的收盤價。對於每一行(即每個行情,每一天)

任何人都可以請幫助我與SQL?

感謝 史蒂夫

+1

你使用了什麼樣的SQL? MySQL的?還有其他的嗎? – 2013-02-25 22:41:27

+0

[您嘗試過什麼?](http://whathaveyoutried.com) – 2013-02-27 21:15:39

回答

1

下面是在SQL的許多方言作品的方式:根據SQL的味道

select t.*, open_price - lastclose as gap 
from (select t.ticker, t.date, t.open_price, t.close_price, 
      (select t.close_price from t t2 where t2.ticker = t.ticker and t2.date < t.date order by DATE desc limit 1 
      ) as lastclose 
     from t 
    ) t 

,該limit 1也可能是select top 1where rownum = 1或。 。 。甚至還有其他的可能性

這使用相關的子查詢來模擬lag()函數,這是你真正需要的。如果你有這個,你可以這樣寫:

select t.*, open_price - lastclose as gap 
from (select t.ticker, t.date, t.open_price, t.close_price, 
      lag(close_price) over (partition by ticker order by date) as lastclose 
     from t 
    ) t 
+0

我剛剛安裝了SQL 2012以使用LAG,並且您的解決方案可以起到一定的作用。謝謝! – SQLseeker 2013-02-27 13:39:29

+0

@ user2109074。 。 。增強的窗口功能在SQL Server 2012中有很大的改進。 – 2013-02-27 14:18:16