我想对我的数据库中的记录进行统计,我想计算用户从/到某个日期时间以及每天每4小时登录系统的平均数
简单示例:我想获得从“2016-09-20 00:00:00”到“2016-09-23 23:59:59”成功登录的平均值,其中应该对这些确定结果次('00:00:00' - '11:59:59')和('12:00:00' - '23:59:59')
这是一个示例数据列表(其中状态1表示成功,0表示不成功):
| id | | driver_id | login_timedate | status |
| 1 | | 1 | '2016-09-20 00:00:11' | 1 |
| 2 | | 2 | '2016-09-20 01:16:09' | 1 |
| 3 | | 2 | '2016-09-20 23:01:16' | 1 |
| 4 | | 3 | '2016-09-21 04:04:59' | 1 |
| 5 | | 3 | '2016-09-21 05:06:59' | 0 |
| 6 | | 2 | '2016-09-21 16:06:59' | 1 |
| 7 | | 1 | '2016-09-22 00:16:59' | 1 |
| 8 | | 2 | '2016-09-23 04:09:22' | 0 |
| 9 | | 1 | '2016-09-23 06:22:59' | 1 |
| 10 | | 3 | '2016-09-23 22:09:22' | 1 |
| 11 | | 1 | '2016-09-24 00:00:22' | 1 |
因此,在这种情况下,我将从(2016年2月20日至2016年9月)获得成功登录总数:8( day1 = 3 ,第2天 = 2,第3天 = 1,第4天 = 2)
每天成功的成功范围( '00:00:00' - '11:59:59'< / strong>) 5 ( day1 = 2, day2 = 1, day3 = 1,第4天 = 1)
平均值: 5/4 = 1.25
每天成功的成功范围( '00:00:00' - '11:59:59'< / strong>) 3 ( day1 = 1,day2 = 0,day3 = 1,day4 = 1)
平均值: 3/4 = 0.75
我已经完成了第一部分,以便在日期时间范围内获得成功登录的总数,这是我的代码(将返回8)
SET @start_date = '2016-09-20';
SET @start_taime = '00:00:00';
SET @end_date = '2016-09-23';
SET @end_time = '23:59:59';
SELECT SUM(`total_logins`.`number_of_success`) FROM (
SELECT COUNT( `login_logs`.`driver_id` ) AS `number_of_success`
FROM `login_logs`
WHERE `login_logs`.`status` = 1
AND
`login_logs`.`login_timedate` >= CONCAT(@start_date, ' ', @start_time)
AND
`login_logs`.`login_timedate` <= CONCAT(@end_date, ' ', @end_time)
GROUP BY `login_logs`.`user_id`
) AS `total_logins`
#UPDATE: 此代码的预期输出:
| total_logins |
| 8 |
我想做下一部分计算相同日期时间范围内的平均登录时间从XX:XX:XX时间到YY:YY:YY时间如下:
- 每天成功的成功范围( '00:00:00' - '11:59:59' ) 5 ( day1 = 2, day2 = 1 ,第3天 = 1,第4天 = 1)
- 平均值: 5/4 = 1.25
#UPDATE: 预期输出修改我的代码以便从('00:00:00' - '11:59:59')获取效果:
| Avrage_00_12 |
| 1.25 |
我应该如何修改代码来实现这部分?
我希望你理解我的问题
感谢您在高级方面提供的帮助
答案 0 :(得分:2)
您可以使用以下查询:
SELECT SUM(`number_of_success`) AS `total_success`,
SUM(`success_range1`) / COUNT(*) AS `average1`,
SUM(`success_range2`) / COUNT(*) AS `average2`
FROM (
SELECT DATE(`login_logs`.`login_timedate`),
COUNT( `login_logs`.`driver_id` ) AS `number_of_success`,
COUNT(CASE
WHEN TIME(`login_logs`.`login_timedate`)
BETWEEN '00:00:00' AND '11:59:59'
THEN 1
END) AS `success_range1`,
COUNT(CASE WHEN TIME(`login_logs`.`login_timedate`)
BETWEEN '12:00:00' AND '23:59:59'
THEN 1
END) AS `success_range2`
FROM `login_logs`
WHERE `login_logs`.`status` = 1
AND
`login_logs`.`login_timedate` >= '2016-09-20 00:00:00'
AND
`login_logs`.`login_timedate` <= '2016-09-23 23:59:59'
GROUP BY DATE(`login_logs`.`login_timedate`)) AS t
<强>输出:强>
total_success, average1, average2
----------------------------------
8, 1.2500, 0.7500