I'm trying to build a database that would help me with technical analysis. But currently I can't move past one hurdle - how to find standing off value in a column?
I don't really even know where to start looking.
I have a dummy table with values like this:
| ID | Values |
| ------------ | ------------ |
| 1 | 26 |
| 2 | 29 |
| 3 | 32 |
| 4 | 34 |
| 5 | 36 |
| 6 | 34 |
| 7 | 33 |
| 8 | 34 |
| 9 | 36 |
| 10 | 37 |
I'd like to find these values as shown here:
Id | Values |
---|---|
1 | 26 |
7 | 33 |
1条答案
按热度按时间2vuwiymt1#
By standoff values, do you mean local minimums and perhaps local maximums? If that is the case, you could look at the
LAG()
andLEAD()
window functions to compare the current value with the prior and next value.If you need to use a larger window (to exclude small jitter), You could use
MIN()
andMAX()
with a qualifier something likeOVER(ORDER BY Id ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING)
and then compare those results with the current value.Because SQL Server limits where window functions can occur (you can't place them in a where clause), you need to wrap these calculations up in a subquery and test the results in your outer query.
A bit of background: Functions like
MIN()
,MAX()
,SUM()
,STDEV()
, andCOUNT()
are normally used to combine data in conjunction with aGROUP BY
clause in a query. These are generally referred to as aggregate functions. However, these aggregate functions (and some others likeLAG()
andLEAD
) can also be used withoutGROUP BY
by adding anOVER()
qualifier that defines their scope. This usage is termed window function. ThatOVER()
qualifier may include a combination ofPARTITION BY
,ORDER BY
, and/orROWS PRECEDING .. FOLLOWING ..
conditions that control the window function behavior.For example:
or
Both of the above produce your desired result. Similar calculations can be done to identifyu local maximums.
See this db<>fiddle for a demo.