SQL Query Compare values in per 15 minutes and display the result per hour

后端 未结 3 570
感动是毒
感动是毒 2021-01-24 02:04

I have a table with 2 columns. UTCTime and Values. The UTCTime is in 15 mins increment. I want a query that would compare the value to the previous value in one hour span and di

3条回答
  •  轮回少年
    2021-01-24 02:50

    Below is the query you need and a working solution Note: I changed the timeframe to 24 hrs

           ;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'
    

提交回复
热议问题