使用SQL查询获取每天的第一次和最后一次

时间:2017-09-01 07:52:02

标签: mysql datetime

我在数据库中有这些数据:

musterid | musterdate          |  userid  | status
---------+---------------------+----------+-------
69       | 2017-09-01 11:58:37 |   50     |   1             
70       | 2017-09-01 12:00:07 |   50     |   1             
71       | 2017-09-01 12:29:15 |   50     |   1     
72       | 2017-09-01 12:31:15 |   50     |   1     
73       | 2017-09-01 09:58:37 |   51     |   1             
74       | 2017-09-01 11:00:07 |   51     |   1             
75       | 2017-09-01 12:29:15 |   51     |   1     
76       | 2017-09-01 07:31:15 |   51     |   1 

我想要这样的输出:

musterid | musterdate          |  userid  | status
---------+---------------------+----------+-------
69       | 2017-09-01 11:58:37 |   50     |   1      
72       | 2017-09-01 12:31:15 |   50     |   1 
73       | 2017-09-01 09:58:37 |   51     |   1 
76       | 2017-09-01 07:31:15 |   51     |   1 

即。我想获得每个用户的第一个和最后一个入场时间。

如何实现这一目标?

我不知道如何创建表来表示数据,所以很抱歉我的演示文稿。

1 个答案:

答案 0 :(得分:0)

复杂查询以获取" 每个用户的第一个和最后一个入场时间":

SELECT 
    t1.*
FROM
    yourtable t1
        LEFT JOIN
    (SELECT 
        MIN(musterdate) AS min_mdate,
        MAX(musterdate) AS max_mdate,
        userid
    FROM
        yourtable
    GROUP BY userid) t2 ON t1.userid = t2.userid
WHERE
    t1.userid = t2.userid
    AND t1.musterdate IN (t2.min_mdate , t2.max_mdate)
ORDER BY userid , musterdate;