2015-12-20 54 views
2

我有庫存符號的歷史數據。如果數據不存在,是否可以獲取最近間隔的數據?

我的問題是,是否有可能獲取數據的最後最近的可能數據的情況下數據不存在的選定日期?

(我正在顯示1D,1WEEK,2WEEK,1MONTH的數據),市場將在週六和週日放假,因此間隔持續變化。 (匹配於間隔,使得最接近的值)

SELECT * from historical_data where symbol_name IN ('WOCKPHARMA','YESBANK') AND 
current_day = DATE_SUB('2015-12-18', INTERVAL 6 DAY) ; 

http://sqlfiddle.com/#!9/3693b/24

+0

之前接近可能「最近」的意思是「最接近以前的」? – Bohemian

+0

最近的當前日期值... – Pawan

+0

@PreethiJain請檢查我的答案,如果給定的日期不匹配,請給出最近的以前的數據 – Thanga

回答

1

限定最近作爲最後一個先前數據爲股票:

查詢

select * 
from historical_data hd 
inner join 
(
SELECT symbol_name, max(current_day) as nearest_day 
from historical_data 
where symbol_name IN ('WOCKPHARMA','YESBANK') 
AND current_day <= DATE_SUB('2015-12-18', INTERVAL 6 DAY) 
group by symbol_name 
) nearest_data 
on hd.symbol_name = nearest_data.symbol_name 
and hd.current_day = nearest_data.nearest_day 
; 

輸出

+-------------+----------------------------+----------+----------+---------+-----------+----------+---------------+-------------+----------------------------+ 
| symbol_name |  current_day   | open_val | high_val | low_val | close_val | last_val | prevclose_val | symbol_name |  nearest_day   | 
+-------------+----------------------------+----------+----------+---------+-----------+----------+---------------+-------------+----------------------------+ 
| WOCKPHARMA | December, 11 2015 00:00:00 |  1611 | 1620  | 1570.3 | 1581.25 | 1579  | 1602.1  | WOCKPHARMA | December, 11 2015 00:00:00 | 
| YESBANK  | December, 11 2015 00:00:00 |  709 | 713.7 | 672.25 | 680.6  | 683.45 | 707.1   | YESBANK  | December, 11 2015 00:00:00 | 
+-------------+----------------------------+----------+----------+---------+-----------+----------+---------------+-------------+----------------------------+ 

sqlfiddle

+0

謝謝,但你能告訴我爲什麼它不吸引任何行,如果我給予intruval爲30天 – Pawan

+0

因爲樣本數據不包含12月前的任何數據,最近的定義爲之前.. – amdixon

+0

好吧,這正是我想要的,非常感謝你.. – Pawan

1

這是你想要的查詢。因爲我給了12月13日這是不存在的,它會給11日的數據是

SELECT distinct * from historical_data as a 
JOIN (select max(current_day) as maxday 
    from historical_data 
    where current_day <= '2015-12-13' and 
    symbol_name IN ('WOCKPHARMA','YESBANK') 
group by symbol_name) as d 
on d.maxday=a.current_day group by symbol_name; 
+0

,但當天沒有YESBANK的數據,則不會提供YESBANK – amdixon

+0

的最新結果。它會返回與當前日期相等或之前的記錄。 – Thanga

+0

如果YESBANK的最近(第13條)記錄是10日,而WOCKPHARMA的最近記錄是11日,則該查詢將僅在11日返回WOCKPHARMA的僅一條記錄 – amdixon

相關問題