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

时间:2012-04-26 01:21:05

标签: sql sql-server count group-by

背景

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

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

提前致谢!

2 个答案:

答案 0 :(得分:10)

猜猜:

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(某些东西)。

答案 1 :(得分: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