Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

SQL Server 2008 R2 - Ilhas e Lacunas


Algo assim deve fazer o trabalho SQL Fiddle

Encontra ilhas de dados sequenciais com o mesmo valor para SIGN e aloca-lhes o mesmo valor de agrupamento usando a técnica de número de linha de Itzik Ben Gan, em seguida, agrupa-os e agrega-os. Os CROSS APPLY ... VALUES desarticula o MIN e 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