用于在一个月中获取每个第一个事件(按日期时间字段)的SQL查询

时间:2013-12-26 12:30:25

标签: mysql sql datetime

我的表格有eventsiddateevent_nameuser_id)和

等记录
(1, '2013-12-01 08:30:00', 'login', 9),
(2, '2013-12-01 08:33:00', 'login', 4),
(3, '2013-12-01 10:22:00', 'logout', 9),
(4, '2013-12-02 08:34:00', 'login', 9),
...

我需要在一个月内的每一天为每个(或指定的)用户获取每个第一个事件。 例如:

2013-12-01 08:30:00, login, 9
2013-12-02 08:34:00, login, 0
...

帮助我构建正确的SQL查询

2 个答案:

答案 0 :(得分:6)

SELECT events.*
FROM
  events INNER JOIN (SELECT user_id,
                            DATE(`date`) as day_event,
                            MIN(`date`) AS first_event
                     FROM   events
                     GROUP BY
                            user_id,
                            DATE(`date`)) fe
  ON events.user_id = fe.user_id
     AND events.`date` = fe.first_event

请参阅小提琴here

如果您只想返回一个月,可以将条件放在子查询中:

(SELECT user_id,
        DATE(`date`) as day_event,
        MIN(`date`) AS first_event
 FROM   events
 WHERE  `date` >= '2013-12-01' AND `date` < '2014-01-01'
 GROUP BY
        user_id,
        DATE(`date`)) fe

答案 1 :(得分:1)

试试这个---

SELECT * 
FROM events 
WHERE id IN (SELECT min(id) 
             FROM events 
             GROUP BY user_id, date)