Unconfirmed, but I would try the following:
var sequence = new[] {1, 6, 3, 5, 2, 8}; var isGoingUp = sequence.First() < sequence.Last();
You can also implement this solution in LINQ by calculating the distances from each point to the corresponding number (from the end).
Implementing this in SQL, however, will be a little more complicated, although you can do it. Here is my attempt and working SQL Fiddle example :
WITH firstValue AS ( SELECT TOP 1 value FROM t ORDER BY id ), lastValue AS ( SELECT TOP 1 value FROM t ORDER BY id DESC ), seqToCheck AS ( SELECT id, CASE WHEN lastValue.value > firstValue.value THEN 0-t.value ELSE t.value END AS value FROM t CROSS JOIN firstValue CROSS JOIN lastValue ), subSequences AS ( SELECT s1.id, COALESCE(MAX(s2.id - s1.id + 1),1) AS distance FROM seqToCheck AS s1 LEFT JOIN seqToCheck AS s2 ON s1.value < s2.value AND s2.id > s1.id GROUP BY s1.id ), longestSubSequence AS ( SELECT TOP 1 id, distance FROM subSequences ORDER BY distance DESC ) SELECT t.value FROM t INNER JOIN longestSubSequence AS l ON t.id >= l.id AND t.id < l.id + l.distance ORDER BY t.id
This assumes that you have a growing column with id that does not contain spaces. You can also do ROW_NUMBER() OVER(ORDER BY xxxxx) if you don't have such a thing.
You can probably make this a little harder to use indexes.
source share