Admitedly不徹底的測試 - 而是用CTE怎麼了,ROWNUMBER()做這兩個步驟
1)確定每行的所有nextsubseqent hi 2)緊鄰的下一行的後續高位小於當前行的任何行 - 那麼當前行必須是本地最大行。
或類似的東西:
begin
DECLARE @highTable as table (high bigint, day date)
declare @securityid int,
@start datetime,
@end datetime
set @start = '1-1-2010'
set @end = '2-1-2010'
select @securityid = id from security where riccode = 'MSFT.OQ' ;
with highsandlows_cte as (
SELECT
ROW_NUMBER() over (order by day) i
, high
, day
, (select top 1 day from quotes nextHi where nextHi.high > today.high and nextHi.day >= today.day and nextHi.securityId = today.securityId order by day asc) nextHighestDay
FROM
quotes today
WHERE
today.securityid = @securityid)
select
*
, (Coalesce((select 1 from highsandlows_cte t2 where t1.i + 1 = t2.i and t1.nextHighestDay > t2.nextHighestDay),0)) as isHigh
from
highsandlows_cte t1
order by
day
end
OK以上是錯誤的 - 這似乎是更多的軌道上:
begin
DECLARE @highTable as table (high bigint, day date)
declare @securityid int,
@start datetime,
@end datetime
set @start = '1-1-2010'
set @end = '2-1-2010'
select @securityid = id from security where riccode = 'MSFT.OQ' ;
with highsandlows_cte as (
SELECT
ROW_NUMBER() over (order by day) i
, high
, day
, low
FROM
quote today
WHERE
today.securityid = @securityid and today.day > convert(varchar(10), @start, 111) and convert(varchar(10), @end, 111) >today.day)
select
cur.day
, cur.high
, cur.low
, case when ((cur.high > prv.high or prv.high IS null)and(cur.high > nxt.high or nxt.high is null)) then 1 else 0 end as isLocalMax
, case when ((cur.low < prv.low or prv.low IS null)and(cur.low < nxt.low or nxt.low is null)) then 1 else 0 end as isLocalMin
from
highsandlows_cte cur left outer join highsandlows_cte nxt
on cur.i + 1 = nxt.i
left outer join highsandlows_cte prv
on cur.i - 1 = prv.i
order by
cur.day
end
獲取雖與重複(高點/低點)問題...
可能的重複:[在SQL中計算「Max Draw Down」](http://stackoverflow.com/questions/4045177/calculating-max-draw-down- in-sql) – 2010-10-28 19:56:00
更多的讚揚,而不是我認爲的重複。 – Ramy 2010-10-28 20:24:17
更多的補充,而不是恭維,我想。 ;) – 2010-10-29 17:37:21