我正在尝试用数据库制作一个android应用程序。但我经验不多。我想要一些帮助来查询我的数据库。我的表格“危机”如下:
ID StartDate EndDate
1 2014-11-05 19:26:16 2014-11-05 19:26:46
2 2014-11-05 19:33:33 2014-11-05 19:33:43
3 2014-11-05 19:33:53 2014-11-06 19:35:14
4 2014-11-06 19:35:24 2014-11-06 19:35:54
5 2014-10-07 09:12:00 2014-10-07 09:12:34
6 2014-10-07 09:18:08 2014-10-07 09:19:11
7 2014-12-05 08:12:12 2014-12-06 08:13:11
8 2014-12-12 10:12:00 2014-12-12 10:12:26
9 2014-12-13 07:33:22 2014-12-13 07:33:59
现在我想知道怎样才能拥有每天、一个月甚至一年的“危机”数字。例如,每日危机的次数:
Days NumberOfCrisis
2014-11-05 3
2014-11-06 1
我也有平均每天,每周,甚至一年的攻击时间。如果有任何帮助,我将不胜感激。
发布于 2015-11-08 10:40:25
这里需要的只是每个组的GROUP BY
和COUNT
,但是在使用组之前,您需要将日期时间转换为:
Year
进行年度计数。month
(或月名)来获取每月计数。WEEK
每周计票。
选择日期(StartDate)作为天数,从危机组按日期计算(ID)为NumberOfCrisis (StartDate);-选择monthname(startDate)为月份,从危机组按月名称(StartDate)计数(ID)为NumberOfCrisis;对于每个危机的平均持续时间,您需要首先使用TIMEDIFF
获取每个危机的持续时间。
SELECT ID, TIMEDIFF(EndDate, StartDate) AS CrisisDuration
FROM crisis
这会给你这样的东西:
然后,您可以使用AVG
获得整个危机期间的平均持续时间:
SELECT SEC_TO_TIME(AVG(TIMEDIFF(EndDate, StartDate))) AS AverageCrisisDuration
FROM crisis;
这会给你这样的东西:
在平均值之后使用SEC_TO_TIME
显示从整数到hh:mm:ss
格式的秒数。
要获得每个月、年份或周的平均值,只需按以下方式添加一个组:
SELECT
Monthname(startdate) AS Month,
SEC_TO_TIME(AVG(TIMEDIFF(EndDate, StartDate))) AS AverageCrisisDuration
FROM crisis
GROUP BY Monthname(startdate);
这将给你:
发布于 2015-11-08 10:42:56
将Group by
与Count
结合使用
SELECT COUNT(startDate) From crisis GROUP BY DATE(startDate)
SELECT COUNT(startDate) From crisis GROUP BY MONTH(startDate)
SELECT COUNT(startDate) From crisis GROUP BY YEAR(startDate)
SELECT COUNT(startDate) From crisis GROUP BY WEEK(startDate)
SELECT COUNT(startDate) From crisis GROUP BY YEAR(startDate)
平均时差使用:-
AVG(timestampdiff(SECOND, startDate, EndDate))
发布于 2015-11-08 10:46:54
如果使用MySQL作为标记,则表示:
危机日数、周末数:
SELECT DATE(startDate) AS Days, COUNT(ID) AS NumberOfCrisis
FROM crisis
GROUP BY DATE(startDate)
SELECT WEEKOFYEAR(startDate) AS Days, COUNT(ID) AS NumberOfCrisis
FROM crisis
GROUP BY WEEKOFYEAR(startDate)
SELECT YEAR(startDate) AS Days, COUNT(ID) AS NumberOfCrisis
FROM crisis
GROUP BY YEAR(startDate)
日平均持续时间、年终周平均时间:
SELECT DATE(startDate), SEC_TO_TIME (AVG(TIME_TO_SEC(TIMEDIFF(EndDate - StartDate))))
FROM crisis
GROUP BY DATE(startDate)
SELECT WEEKOFYEAR(startDate), SEC_TO_TIME (AVG(TIME_TO_SEC(TIMEDIFF(EndDate - StartDate))))
FROM crisis
GROUP BY WEEKOFYEAR(startDate)
SELECT YEAR(startDate), SEC_TO_TIME (AVG(TIME_TO_SEC(TIMEDIFF(EndDate - StartDate))))
FROM crisis
GROUP BY YEAR(startDate)
使用的功能:https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
https://stackoverflow.com/questions/33593033
复制相似问题