2012-03-31 21 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です。私は各セキュリティのための特定の時間範囲からのデータだけを取得しようとしています。最初に私はminとmaxとの違いを見つけて、最終的には、このような最小値よりも10%以上である値を見つけ、その後、各セキュリティIDの最小値と最大値を見つけるためのクエリを実行します。

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に関するご質問ですか?彼らは同じことではありません。 –

答えて

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

また、式を簡略化するために、式に対して少しの代数を行うことができます。私はそれを読者に練習として残す。 ;) –

関連する問題