为组中的每个条目运行总计

时间:2010-01-28 05:30:33

标签: mysql

我的表结构看起来像这样......

| 2010-01-28 10:00:01 | Delhi | Application | up     | 
| 2010-01-28 10:00:01 | Delhi | Mysql       | up     | 
| 2010-01-28 10:00:01 | Delhi | LAN         | down   | 
| 2010-01-28 10:00:01 | Delhi | WAN         | up     | 
| 2010-01-28 10:15:01 | Delhi | Application | up     | 
| 2010-01-28 10:15:01 | Delhi | Mysql       | up     | 
| 2010-01-28 10:15:01 | Delhi | LAN         | down   | 
| 2010-01-28 10:15:01 | Delhi | WAN         | up     | 
| 2010-01-28 10:30:01 | Delhi | Application | up     | 
| 2010-01-28 10:30:01 | Delhi | Mysql       | up     | 
| 2010-01-28 10:30:01 | Delhi | LAN         | up   | 
| 2010-01-28 10:30:01 | Delhi | WAN         | up     | 

LAN的总停机时间为30分钟。

| 2010-01-28 10:00:01 | Delhi | LAN         | down   | 
| 2010-01-28 10:15:01 | Delhi | LAN         | down   | 
| 2010-01-28 10:30:01 | Delhi | LAN         | up   | 

有没有办法按计算运行总计的方式计算总停机时间?

2 个答案:

答案 0 :(得分:1)

似乎每个报告周期恰好是15分钟,每个应用都会列出,所以快速破解可以是:

SELECT COUNT(state)*15 as downtime,Application FROM stats WHERE state='down' GROUP BY Application

答案 1 :(得分:-1)

您需要查看连续记录,并计算上一个条目“已关闭”的时间。在SQL Server中,您可以这样做......我认为它在mysql中类似

With OrderedRows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY System ORDER BY StatusTime) AS RowNum
FROM yourTable
)
SELECT o_this.System, 
  SUM(DATEDIFF(second, o_this.StatusTime, o_next.StatusTime)) AS DownTimeSeconds
FROM OrderedRows o_this
  JOIN
  OrderedRows o_next
  ON o_next.System = o_this.System
  AND o_next.RowNum = o_this.RowNum + 1
WHERE o_this.Status = 'down'
GROUP BY o_this.System;

如果没有排名功能,请尝试以下内容:

SELECT t.System, 
  SUM(DATEDIFF('s', 
      t.StatusTime, 
      (SELECT MIN(t_next.StatusTime) 
       FROM yourTable AS t_next
       WHERE t_next.System = t.System
       AND t_next.StatusTime > t.StatusTime
      )
   )) AS DownTimeSeconds
FROM yourTable as t
WHERE t.Status = 'down'
GROUP BY t.System;

但事件可能会因汇总而不是聚合。