Noget som dette burde gøre jobbet SQL Fiddle
Den finder øer med sekventielle data med samme værdi for SIGN
og tildeler dem den samme grupperingsværdi ved hjælp af Itzik Ben Gans rækkenummerteknik og grupperer dem derefter og aggregerer dem. CROSS APPLY ... VALUES
deaktiverer MIN
og 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