小编典典

SQL Server:按小时和星期几的平均计数

sql

背景

我在SQL
Server环境中设置了一个表,该表包含我正在跟踪的各种活动的日志。特定的日志项使用唯一的代码对正在发生的活动进行分类,并且日期时间字段跟踪该活动的发生时间。

问题

我想使用单个查询或存储过程来获取平均每小时的活动计数,并按一周中的星期几进行分组。例子:

Day      | Hour | Average Count
-------------------------------
Monday   | 8    | 5
Monday   | 9    | 5
Monday   | 10   | 9
...
Tuesday  | 8    | 4
Tuesday  | 9    | 3
...etc

现在,我有一个查询设置,它每天会吐出每小时的计数,但是我的问题是要进一步向前发展,并在一周中的某天取得平均水平。这是我当前的查询:

SELECT CAST([time] AS date) AS ForDate,
   DATEPART(hour, [time]) AS OnHour,
   COUNT(*) AS Totals
FROM [log] WHERE [code] = 'tib_imp.8'
GROUP BY CAST(time AS date),
   DATEPART(hour,[time])
   ORDER BY ForDate Asc, OnHour Asc

关于如何实现此目标的任何建议?

提前致谢!


阅读 219

收藏
2021-04-17

共1个答案

小编典典

在这里猜测:

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;

同样,如果没有数据,我可能会再次在墙上扔一些泥浆,希望它能粘住,但也许您需要的是:

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;

这也将产生基于整数的平均值,因此您可能希望将内部查询上的Totals别名转换为DECIMAL(something,something)。

2021-04-17