Something like this should do the job SQL Fiddle
It finds islands of sequential data with the same value for SIGN
and alllocates them the same grouping value using Itzik Ben Gan's row number technique then groups them and aggregates them. The CROSS APPLY ... VALUES
unpivots the MIN
and MAX
;WITH T1
AS (SELECT *,
ROW_NUMBER() OVER (PARTITION BY SIGN(PctGain)
ORDER BY WSeqKey) - WSeqKey AS Grp
FROM YourTable),
T2
AS (SELECT MIN(WSeqKey) AS BeginSeq,
MAX(WSeqKey) AS EndSeq,
SIGN(PctGain) AS Sign
FROM T1
GROUP BY Grp,
SIGN(PctGain))
SELECT CASE Sign
WHEN -1 THEN 'Negative'
WHEN 0 THEN 'Equal'
WHEN 1 THEN 'Positive'
END AS [Sign],
Descriptor,
SeqKey
FROM T2
CROSS APPLY (VALUES('Begin', BeginSeq),
('End', EndSeq)) V(Descriptor, SeqKey)
ORDER BY SeqKey