2012-03-31 161 views
0

我有一個數據庫中證券價格的數據集。該數據的結構是這樣的:基於2條件的SQL匹配行

id  security_id  time_to_maturity  price 
001   01    1.5    100.45 
002   01    1.3    101.45 
003   01    1.1    102.45 
004   01    1.02    101.45 
005   01    1.0    101.45 
006   03    22.3    94.45 
007   03    22.1    96.45 
008   03    21.8    98.45 
009   05    4.2    111.45 
010   05    4.1    112.45 
011   05    3.8    111.45 
... 

id是row_idsecurity_id是每個安全的ID。我試圖從每個安全性的特定時間範圍獲取數據。首先,我運行一個查詢查找每個安全ID的最小值和最大值,然後找到最小和最大和最後的區別找到一個值,該值大於最小像這樣10%以上的是:

SELECT security_id, MIN(time_to_maturity), MAX(time_to_maturity), 
    MAX(time_to_maturity) - MIN(time_to_maturity) tDiff, 
    ((MAX(time_to_maturity) - MIN(time_to_maturity)) * .1) + MIN(time_to_maturity) 
    FROM db1 
    group by security_id 
    order by security_id 

這使我下面的:

security_id min()  max()  diff  min+(diff*.1) 
    01    1.0  1.5  .5   1.05 
    03   21.8  22.3  .5   21.85 
    05    3.8  4.2  .4   3.84 

最後,我想要做的是從主數據集只有那些行每個security_idtime_to_maturity is < min+(diff*.1)選擇。

我不知道如何構造它,因爲我覺得我需要一個循環來通過security_id子集數據,然後通過time_to_maturity is < min+(diff*.1)

答案會是這個樣子:

id  security_id  time_to_maturity  price 
004   01    1.02    101.45 
005   01    1.0    101.45 
008   03    21.8    98.45 
011   05    3.8    111.45 

有什麼建議?

+0

是您的關於MySQL的問題,或有關SQL Server?他們不是一回事。 – 2012-03-31 03:24:12

回答

1
SELECT A.id,B.security_id,A.time_to_maturity,A.price 
FROM db1 A, 
(
SELECT security_id, MIN(time_to_maturity) AS min_time_to_maturity, MAX(time_to_maturity) AS max_time_to_maturity, 
    MAX(time_to_maturity) - MIN(time_to_maturity) tDiff, 
    ((MAX(time_to_maturity) - MIN(time_to_maturity)) * .1) + MIN(time_to_maturity) 
    FROM db1 
    group by security_id 
    order by security_id 
) B 
WHERE A.security_id = B.security_id 
    AND A.time_to_maturity < (B.min_time_to_maturity+(B.tdiff*0.1)); 

PS:這隻適用於MYSQL。

1

你沒有說你是什麼版本的SQL Server上,但假設它是2005+,你可以使用一個公用表表達式:

with cte as ( 
    SELECT security_id, 
     ((MAX(time_to_maturity) - MIN(time_to_maturity)) * .1) + MIN(time_to_maturity) as threshold 
    FROM db1 
    group by security_id 
) 
select id, db1.security_id, time_to_maturity, price 
from db1 
inner join cte 
    on db1.security_id = cte.security_id 
where time_to_maturity < threshold 
+1

另外,我會注意到,你可以在你的表達式上做一個小的代數來簡化它。我把這個作爲練習留給讀者。 ;) – 2012-03-31 04:59:04