SQL计数TIMESTAMPDIFF值,按日期条目排序

时间:2015-10-13 11:03:57

标签: mysql sql

我很难找到合适的查询,请帮忙。 解释:我有一个表,根据登录状态插入行。 该表看起来像这样(部分):

+----------+------------+-----------+---------+---------------------+
| username | view_start | view_stop | action  |     action_time     |
+----------+------------+-----------+---------+---------------------+
| adrian   | 10:00:00   |           | log-in  | 2015-09-01/10:00:00 |
| adrian   | 10:00:00   | 10:35:00  | log-off | 2015-09-01/10:35:00 |
| john     | 12:00:00   |           | log-in  | 2015-09-01/12:00:00 |
| john     | 12:00:00   | 12:45:00  | log-off | 2015-09-01/12:45:00 |
+----------+------------+-----------+---------+---------------------+

我想实现以下目标:

  • 计算view_startview_stop之间对具有操作log-off的行(他们最后执行的操作)的差异

  • 根据白天时间(当天用户登录的总时间)订购该列表

到目前为止我取得的成就:

我计算并按天计算总用户数

SELECT DATE(action_time) Date, COUNT(DISTINCT username) totalCOunt
FROM audit_data
GROUP BY DATE(action_time)

输出:

+------------+------------+
|    date    | totalCOunt |
+------------+------------+
| 2015-09-01 |          5 |
| 2015-09-02 |          3 |
| 2015-09-03 |          1 |
| 2015-09-04 |          7 |
+------------+------------+

我计算了两个日期之间的差异

SELECT view_start, view_stop,username, TIMESTAMPDIFF(MINUTE, view_start, view_stop) AS MinuteDiff 
FROM audit_data 
WHERE action = "off-line" 
ORDER BY username

+------------+-----------+----------+------------+
| view_start | view_stop | username | MinuteDiff |
+------------+-----------+----------+------------+
| 10:00:00   | 11:00:00  | adrian   |         60 |
| 11:00:00   | 12:00:00  | adrian   |         60 |
| 12:00:00   | 13:00:00  | john     |         60 |
| 13:00:00   | 14:00:00  | george   |         60 |
+------------+-----------+----------+------------+

我想"结合"这些查询用于计算用户每天登录的总时间:

+-------------+---------------------+
|     day     | totalDiff (minutes) |
+-------------+---------------------+
| 2015-09-01  |                 120 |
| 2015-09-02  |                  38 |
| 2015-09-03  |                  76 |
| 2015-09-04  |                 156 |
+-------------+---------------------+

重要细节:用户可以每天多次登录

我试过的查询: SELECT DATE(action_time) Date, COUNT(SELECT SUM(SELECT TIMESTAMPDIFF(MINUTE, view_start, view_stop) )) totalCOunt FROM audit_data GROUP BY DATE(action_time)

1 个答案:

答案 0 :(得分:0)

根据您的描述,您只需要将分钟数相加:

SELECT DATE(action_time) Date 
   ,COUNT(DISTINCT username) totalCOunt 
   ,SUM(TIMESTAMPDIFF(MINUTE, view_start, view_stop)) AS totalDiff 
FROM audit_data 
GROUP BY DATE(action_time)
ORDER BY 1

请参阅Fiddle