SELECT
COUNT(t1.tid) AS count,
u.user_name,
SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(t1.endtime,t1.endtime)))/COUNT(t1.endtime)) AS `avg`,
MAX(TIMEDIFF(t1.endtime,t1.starttime)) AS `max`,
MIN(TIMEDIFF(t1.endtime,t1.starttime)) AS `min`,
CONCAT(
IF(t1.starttime>=(NOW() - INTERVAL 15 MINUTE), '15', ''),
IF(t1.starttime>=(NOW() - INTERVAL 30 MINUTE), '30', ''),
IF(t1.starttime>=(NOW() - INTERVAL 1 HOUR), 'H', ''),
IF(t1.starttime>=(NOW() - INTERVAL 1 DAY), 'D', ''),
IF(t1.starttime>=DATE_FORMAT(SUBDATE(NOW(), INTERVAL WEEKDAY(NOW()) DAY), '%Y-%m-%d'), 'W', ''),
IF(t1.starttime>=CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') AS DATE), 'M', '')
) AS period,
t1.starttime
FROM table1 t1
LEFT OUTER JOIN `user` u ON u.id = t1.user_id
WHERE t1.starttime >= CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') AS DATE)
GROUP BY user_name, period
以上是我所做的示例查询。我的目的是获得各种时间线的结果。即获得最后15分钟,1小时,1天,1周,1个月的计数,分钟,最大等等。
所以我想要的是结果如下:
+--------------+--------------+-----------------+--------------+-----------------+
| period | count | user | min | max |
+--------------+--------------+-----------------+--------------+-----------------+
| 15mins | 12 | test_user1 | 00:00:45 | 00:01:45 |
| 15mins | 12 | test_user2 | 00:00:45 | 00:01:45 |
| 15mins | 12 | test_user3 | 00:00:45 | 00:01:45 |
| 15mins | 12 | test_user4 | 00:00:45 | 00:01:45 |
| 15mins | 12 | test_user5 | 00:00:45 | 00:01:45 |
| 30mins | 15 | test_user1 | 00:01:45 | 00:11:45 |
| 30mins | 15 | test_user2 | 00:01:45 | 00:11:45 |
| 30mins | 16 | test_user3 | 00:04:45 | 00:11:45 |
| 30mins | 18 | test_user4 | 00:09:45 | 00:11:45 |
| 30mins | 19 | test_user10 | 00:07:45 | 00:11:45 |
| 30mins | 14 | test_user11 | 00:04:45 | 00:11:45 |
| 30mins | 15 | test_user12 | 00:00:45 | 00:11:45 |
| 1day | 100 | test_user1 | 01:00:45 | 01:11:45 |
+--------------+--------------+-----------------+--------------+-----------------+
t1.starttime是日期时间。我们根据当前服务器时间得到结果。
答案 0 :(得分:0)
如果您的间隔是嵌套的(在1小时内30分钟内15分钟等),那么您无法避免工会,您的查询(我简化了一下)将如下所示:
select count(t1.tid) as count, '15 min' period, userid ,
SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(t1.endtime,t1.endtime)))/COUNT(t1.endtime)) AS `avg`,
MAX(TIMEDIFF(t1.endtime,t1.starttime)) AS `max`,
MIN(TIMEDIFF(t1.endtime,t1.starttime)) AS `min`
from t1
where timestampdiff(minute,t1.starttime,now()) < 15
group by userid
UNION
select count(t1.tid) as count, '30 min' , userid ,
SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(t1.endtime,t1.endtime)))/COUNT(t1.endtime)) AS `avg`,
MAX(TIMEDIFF(t1.endtime,t1.starttime)) AS `max`,
MIN(TIMEDIFF(t1.endtime,t1.starttime)) AS `min`
from t1
where timestampdiff(minute,t1.starttime,now()) < 30
group by userid
UNION
select count(t1.tid) as count, '60 min', userid ,
SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(t1.endtime,t1.endtime)))/COUNT(t1.endtime)) AS `avg`,
MAX(TIMEDIFF(t1.endtime,t1.starttime)) AS `max`,
MIN(TIMEDIFF(t1.endtime,t1.starttime)) AS `min`
from t1
where timestampdiff(minute,t1.starttime,now()) < 60
group by userid
/* and so on */
order by period, userid