sql >> Base de Datos >  >> Database Tools >> SSMS

Consulta SQL Compare los valores en cada 15 minutos y muestre el resultado por hora

A continuación se muestra la consulta que necesita y una solución funcional Nota:Cambié el plazo a 24 horas

       ;with SourceData(HourTime, Value, RowNum)
  as
  (
    select 
      datepart(hh, UTCTime) HourTime, 
      Value, 
      row_number() over (partition by datepart(hh, UTCTime) order by UTCTime) RowNum
    from foo
    union 
    select 
        datepart(hh, UTCTime) - 1 HourTime, 
        Value,
        5
    from foo
    where datepart(mi, UTCTime) = 0
  )
  select cast(A.HourTime as varchar) + ':00' UTCTime, sum(case when A.Value = B.Value then 1 else 0 end) ConstantValues
  from SourceData A
   inner join SourceData B on A.HourTime = B.HourTime and
                           (B.RowNum = (A.RowNum - 1))
  group by cast(A.HourTime as varchar) + ':00'