在每个ID Mysql的2个时间戳之间获得前N行

时间:2015-08-05 21:00:29

标签: mysql sql group-by greatest-n-per-group sqlparameters

我有如下表,start_t是我在unixtime中的时间戳,例如(1438326239412)但为了简单起见,我在这里写了一些小数字:

user_id | start_t | duration
1         12           1
1         15           2
1         4            5
2         9            6
2         10           5
3         9            6       

我想在两个时间戳之间为每个user_id获得前N行。这是我的代码,但它返回的超过我想要的限制:

SELECT us.* FROM (SELECT us.*, (@rn := if(@i = us.user_id, @rn + 1, if(@i := us.user_id, 1, 1) ) ) AS seqnum FROM user_stats us,tourn_user tu CROSS JOIN (SELECT @rn := 0, @i := -1) params WHERE (us.start_t+us.duration)<= 20 AND us.start_t >= 4 ORDER BY us.user_id, start_t ASC ) us WHERE seqnum <= 1

对于该特定示例,结果应如下所示:

user_id | start_t | duration
1         4            5
2         9            6
3         9            6       

1 个答案:

答案 0 :(得分:0)

以下是有人想要的解决方案:

select us.* from (select us.*, (@rn := if(@i = us.user_id, @rn + 1, if(@i := us.user_id, 1, 1) ) ) as seqnum from user_stats us cross join (select @rn := 0, @i := -1) params where (us.start_t+us.duration)<= 15 AND us.start_t >= 0 order by us.user_id, start_t ASC ) us where seqnum <= 1