我有一个记录表,用于记录各种数据。有时,每个时间戳会创建多个行,有时可能需要几秒钟的时间,更多的日志条目才能到达表。我想做的是将一组记录分组在一起,彼此之间相隔2-3分钟,并计算这两项的秒数差异。并且,如果可能,请选择最受欢迎的“类别”。
我真的不确定该怎么做,但说我的数据是这样的:
datetime message category
2019-04-03 12:30:00 etc/bar/x did something b
2019-04-03 12:30:00 there was a failure b
2019-04-03 12:30:01 xyz is corrupt a
2019-04-03 12:31:00 something different a
2019-04-03 12:31:00 drive on mnt/x is full c
2019-04-03 12:31:00 extra info b
2019-04-03 12:31:05 /etc/bar/foo did something c
2019-04-03 12:40:01 foo output x a
2019-04-03 12:41:30 another message a
我想要得到的是:
Total time category
00:01:05 b # Note this is 1 min, 5 secs, not 1:05am!
00:01:29 a # Note this is 1 min 29 secs, not 1:29am!
第一个列是hh:mm:ss(不是时间戳而是时间的计数,所以1分5秒)。关于如何解决这个问题有什么想法吗?
或者,或者,我很高兴获得上下限时间输出,例如:
Time between avg category
2019-04-03 12:30:00 b # Note this is the start timestamp, 12:30:00pm
2019-04-03 12:31:05 c # Note this is the end timestamp, 12:31:05pm
2019-04-03 12:40:01 a
2019-04-03 12:41:30 a
答案 0 :(得分:1)
对于第一个输出,您可以尝试以下查询:
SELECT SEC_TO_TIME(TIME_TO_SEC(MAX(timestamp))-TIME_TO_SEC(MIN(timestamp))) AS "Total Time",
Category FROM your_table GROUP BY category;
据此TIME_TO_SEC
将您的TIME
值转换为总秒数。因此,每个类别的MAX(timestamp)
减去MIN(timestamp)
值(均转换为秒值)。然后,通过使用SEC_TO_TIME
操作将其结果转换回时间。因此,您将获得hh:mm:ss格式的Total Time
。
对于第二个输出,您可以尝试以下查询:
SELECT MIN(timestamp) AS "Timestamp",category
FROM your_table GROUP BY category UNION
SELECT MAX(timestamp) AS "Timestamp",category
FROM your_table GROUP BY category ORDER BY category;
在联合查询顶部获得MIN(timestamp)
值,在下面获得MAX(timestamp)
值。以ORDER BY category
结尾。
如果您有DATE
列,并且想要按日期分隔每个类别,只需在选择和分组依据中添加该列即可。例如:
SELECT Date,
SEC_TO_TIME(TIME_TO_SEC(MAX(timestamp))-TIME_TO_SEC(MIN(timestamp))) AS "Total Time",
Category FROM your_table GROUP BY date,category;
AND
SELECT Date,MIN(timestamp) AS "Timestamp",category
FROM your_table GROUP BY category UNION
SELECT Date,MAX(timestamp) AS "Timestamp",category
FROM your_table GROUP BY Date,category ORDER BY date,category;
编辑: 在下面尝试以下查询:
SELECT * FROM
(SELECT * FROM your_table
WHERE category="b"
GROUP BY DATE(timestamp),UNIX_TIMESTAMP(timestamp) DIV 180) sub1
LEFT JOIN
(SELECT * FROM your_table WHERE category="b") sub2
ON sub1.category=sub2.category AND DATE(sub1.timestamp)=DATE(sub2.timestamp)
AND sub1.timestamp<>sub2.timestamp
AND sub2.timestamp BETWEEN sub1.timestamp AND sub1.timestamp + INTERVAL 3 MINUTE;