I'm trying to get the number of seconds a user has had his/her account enabled during a specific 7 day time period.
This can be easily done using TIMEDIFF
- but what makes this tricky (and not answered anywhere else):
[A] The account was enabled once our time period started (id
2) and should be considered enabled since start date.
[B] There is no enabled_end
set for id
5, meaning account is currently enabled and should be considered enabled until end date.
Her is the basic query:
SELECT SEC_TO_TIME(sum(TIME_TO_SEC(TIMEDIFF(enabled_end, enabled_start)))) AS total_seconds from logs WHERE user_id = '123' and enabled_start >= '2022-04-22 00:00:00' and enabled_end <= '2022-04-27 23:59:59'
So above query will fail to include id
2 as described in [A] and id
5 as described in [B]
id | user_id | enabled_start | enabled_end |
---|---|---|---|
5 | 123 | 2022-04-26 12:13:38 | NULL (=account is still enabled) |
4 | 123 | 2022-04-25 15:22:36 | 2022-04-25 17:32:11 |
3 | 123 | 2022-04-24 11:16:46 | 2022-04-25 05:10:08 |
2 | 123 | 2022-04-15 14:44:00 | 2022-04-23 10:58:53 |
1 | 123 | 2022-03-29 16:44:15 | 2022-04-04 11:22:39 |
0 | 123 | 2022-03-24 13:44:15 | 2022-03-25 09:11:39 |