8

背景

我在 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

关于我如何做到这一点的任何建议?

提前致谢!

4

2 回答 2

13

在这里猜测:

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)。

于 2012-04-26T01:47:35.080 回答
0
; WITH a AS (
    SELECT CAST([time] AS date) AS ForDate
       , DATEPART(hour, [time]) AS OnHour
       , txtW=DATENAME(WEEKDAY,[time])
       , intW=DATEPART(WEEKDAY,[time])
       , Totals=COUNT(*)
    FROM [log] WHERE [code] = 'tib_imp.8'
    GROUP BY CAST(time AS date)
    , DATENAME(WEEKDAY,[time])
    , DATEPART(WEEKDAY,[time])
    , DATEPART(hour,[time])
)
SELECT [Day]=txtW
, [Hour]=OnHour
, [Average Count]=AVG(Totals)
FROM a
GROUP BY txtW, intW, OnHour
ORDER BY intW, OnHour
于 2012-04-26T02:27:28.137 回答