以1分钟为间隔获得平均值和最大值T-SQL

时间:2018-04-30 20:20:58

标签: sql-server tsql

我有一个查询,以1分钟为间隔提取记录数。我想比较平均值和最后值。

我只得到总数是计数(1)及其有效值。平均值和最大值始终返回1,这是不准确的。

这个SQL中是否有我缺少的东西?

SELECT 
    FORMAT(timestamp, 'hh:mm') AS tm, 
    AVG(1) AS avgOccurances, 
    MAX(1) AS maxocc, 
    COUNT(1) AS total 
FROM   
    [history] 
WHERE  
    timestamp BETWEEN '2018-04-16 14:00:00.707' AND '2018-04-18 15:00:00.707' 
    AND result = 'F' 
GROUP BY 
    FORMAT(timestamp, 'hh:mm') 
ORDER BY 
    tm ASC 

结果

01:00   1   1   13
01:01   1   1   10
01:02   1   1   11
01:03   1   1    7
01:04   1   1   13
01:05   1   1    7
01:06   1   1   14
01:07   1   1   11
01:08   1   1   12
01:09   1   1   10
01:10   1   1    5
01:11   1   1    6
01:12   1   1    8
01:13   1   1   13
01:14   1   1    9
01:15   1   1    8
01:16   1   1    2
01:17   1   1   10
01:18   1   1    9
01:19   1   1   13
01:20   1   1    9
01:21   1   1    8
01:22   1   1   14
01:23   1   1   10

1 个答案:

答案 0 :(得分:2)

以下查询假设每行应具有以下内容:

  • 每分钟计数
  • 前一分钟的每分钟计数
  • 计算出现次数最多的分钟

如果不正确,请告诉我。这是查询:

WITH countbyminute AS (
  SELECT
    FORMAT(timestamp, 'hh:mm') AS tm,
    COUNT(*) AS occurences
  FROM history
  GROUP BY FORMAT(timestamp, 'hh:mm')
)
SELECT
  tm,
  occurrences,
  LAG(occurrences) OVER (ORDER BY TIMESTAMP) AS priorocc,
  MAX(occurrences) OVER () AS maxocc
FROM countbyminute
ORDER BY tm;

我建议使用HH:mm作为格式字符串,这将使用24小时制(下午1:00作为13:00)重新计算小时数。