如何每天对unix时间进行分组?

时间:2016-06-20 01:50:43

标签: mysql sql

我有一张这样的表:

// requests
+----+----------+-------------+
| id | id_user  |  unix_time  |
+----+----------+-------------+
| 1  | 2353     | 1339412843  |
| 2  | 2353     | 1339412864  |
| 3  | 5462     | 1339412894  |
| 4  | 3422     | 1339412899  |
| 5  | 3422     | 1339412906  |
| 6  | 2353     | 1339412906  |
| 7  | 7785     | 1339412951  |
| 8  | 2353     | 1339413640  |
| 9  | 5462     | 1339413621  |
| 10 | 5462     | 1339414490  |
| 11 | 2353     | 1339414923  |
| 12 | 2353     | 1339419901  |
| 13 | 8007     | 1339424860  |
| 14 | 7785     | 1339424822  |
| 15 | 2353     | 1339424902  |
+----+----------+-------------+

我想根据分开的日期对unix_time列进行分组。实际上,我正在尝试为特定用户制作此内容:

https://docs.angularjs.org/error/ng/areq?p0=controllers%2FsomeNameController&p1=not%20a%20function,%20got%20undefined

如您所见,我需要为用户提供两个号码:

  • 用户占地面积为requests
  • 的所有天数
  • 最大连续日数

我该怎么做?

实际上我可以使用WHERE id_user = :id来选择用户的行。我可以按SUM()计算天数。通过使用MAX(),我可以计算出最大的连续范围。我只需要对那些unix时间进行分组。

2 个答案:

答案 0 :(得分:2)

使用可以使用from_unixtime()提取日期。然后你可以使用变量计算天数:

select id_user, d,
       (@rn := if(@di = concat_ws(':', d - interval 1 day, id_user), @rn + 1,
                  if(@di :=  concat_ws(':', d, id_user), 1, 1)
                 )
       ) as rn
from (select id_user, date(from_unixtime(unix_time)) as d
      from t
      group by id_user, d
     ) cross join
     (select @di := '', @rn := 0) params
order by id_user, d;

从这里到摘要只是一个聚合:

select id_user, count(*) as numdays, max(rn) as maxconsecutive
from (select id_user, d,
             (@rn := if(@di = concat_ws(':', d - interval 1 day, id_user), @rn + 1,
                        if(@di :=  concat_ws(':', d, id_user), 1, 1)
                       )
             ) as rn
      from (select id_user, date(from_unixtime(unix_time)) as d
            from t
            group by id_user, d
           ) cross join
           (select @di := '', @rn := 0) params
      order by id_user, d
     ) ud
group by id_user;

Here是一个说明代码的SQL小提琴。

答案 1 :(得分:2)

请试一试:

id_user Total_Visits    Maximum_Consecutive_Visits
2353        7                    2
3422        2                    2
5462        3                    2
7785        2                    1
8007        1                    1

SQL FIDDLE DEMO

<强>输出:

最终输出如下所示:

WHERE clause in the inner query

修改

要获得特定用户的输出,您需要添加{{1}}。

请检查

SQL FIDDLE