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

SQL mantendo a contagem de ocorrências através de uma janela deslizante


Use a opção com CTE , CROSS APPLY operador e ROW_NUMBER função de classificação
 ;WITH cte AS
 (
  SELECT [Date], Code
  FROM dbo.YourTable  
  GROUP BY [Date], Code
  )
  SELECT c.Date, c.Code, o.Occurrences
  FROM cte c 
    CROSS APPLY (
                 SELECT t2.[Date], t2.Code,
                        ROW_NUMBER() OVER(PARTITION BY c.[Date] ORDER BY t2.[Date]) AS Occurrences        
                 FROM dbo.YourTable t2
                 WHERE c.Code = t2.Code
                   AND DATEDIFF(day, t2.[Date], c.[Date]) BETWEEN 0 AND 1
                 ) o
  WHERE c.Code = o.Code AND c.[Date] = o.[Date] 
  ORDER BY c.[Date]

Demonstração em SQLFiddle

Para melhorar o desempenho, use este índice
CREATE INDEX x ON dbo.YourTable([Date], Code)