SQL Server: Average counts by hour and day of week

前端 未结 2 928
Happy的楠姐
Happy的楠姐 2021-02-09 00:13

Background

I have a table set up in a SQL Server environment that contains a log of various activity that I\'m tracking. Particular log items use unique codes to categ

2条回答
  •  情深已故
    2021-02-09 00:47

    Guessing here:

    SELECT [Day], [Hour], [DayN], AVG(Totals) AS [Avg]
    FROM
      (
            SELECT 
              [Day]  = DATENAME(WEEKDAY, [time]),
              [DayN] = DATEPART(WEEKDAY, [time]),
              [Hour] = DATEPART(HOUR,    [time]),
              Totals = COUNT(*)
            FROM dbo.[log] 
                WHERE [code] = 'tib_imp.8'
            GROUP BY 
              DATENAME(WEEKDAY, [time]),
              DATEPART(WEEKDAY, [time]),
              DATEPART(HOUR,    [time])
      ) AS q
    GROUP BY [Day], [Hour], [DayN]
    ORDER BY DayN; 
    

    Again, without data, I might once again be throwing a handful of mud at the wall and hoping it sticks, but perhaps what you need is:

    SELECT [Day], [Hour], [DayN], AVG(Totals) AS [Avg]
    FROM
    (
        SELECT 
      w = DATEDIFF(WEEK, 0, [time]),
          [Day]  = DATENAME(WEEKDAY, [time]),
          [DayN] = DATEPART(WEEKDAY, [time]),
          [Hour] = DATEPART(HOUR,    [time]),
          Totals = COUNT(*)
        FROM dbo.[log] 
          WHERE [code] = 'tib_imp.8'
        GROUP BY 
      DATEDIFF(WEEK, 0, [time]),
          DATENAME(WEEKDAY, [time]),
          DATEPART(WEEKDAY, [time]),
          DATEPART(HOUR,    [time])
      ) AS q
    GROUP BY [Day], [Hour], [DayN]
    ORDER BY DayN; 
    

    This is also going to produce integer-based averages, so you may want to cast the Totals alias on the inner query to DECIMAL(something,something).

提交回复
热议问题