2012-03-31 2 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이다. 각 보안에 대해 특정 시간 범위의 데이터 만 가져 오려고합니다.

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 

이주는 : 우선 각 보안 ID의 최소 및 최대를 찾을 수있는 쿼리를 실행, 다음과 같은 최소 10 % 이상 값을 찾아 마지막으로 최소 및 최대 사이의 차이를 찾을 수 나 다음

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)); 

추신 : 이것은 MYSQL에서만 작동합니다.

1

당신이 있었지만, 가정 당신은 공통 테이블 표현식 사용할 수 있습니다 2005 +의 SQL 서버의 버전 당신은 말하지 않았다 :

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

또한 간단히하기 위해 임계 값에 대한 식에 약간의 대수를 사용할 수 있습니다. 나는 그것을 독자에게 연습으로 남겨 둡니다. ;) –

관련 문제