1

我有来自考勤程序的mysql数据(表),如下所示:

+--------+--------------------+-----------+
| userid | checktime          | checktype | 
+-----------------------------+-----------+
|      1 | 26/04/2013 8:05:17 | I         |
|      2 | 26/04/2013 8:05:17 | I         |
|      2 | 26/04/2013 17:28:47| O         |
|      3 | 26/04/2013 17:32:24| O         |
+-----------------------------------------+

我想要这样的预览:

+--------+--------------------+---------------------+
| userid | Login time         | Logout time         | 
+-----------------------------+---------------------+
|      1 | 26/04/2013 8:05:17 | Null                |
|      2 | 26/04/2013 8:05:17 | 26/04/2013 17:28:47 |
|      3 | Null               | 26/04/2013 17:32:24 |
+---------------------------------------------------+

我应该如何编写查询来预览此输出?任何建议都会对我有所帮助。请帮助...

4

1 回答 1

1

使用您提供的信息,此查询应该这样做:

SELECT
  userid,
  max(if(checktype = 'I', checktime, NULL)) loginTime,
  max(if(checktype = 'O', checktime, NULL)) logoutTime
FROM t
GROUP BY userid

输出:

| USERID |          LOGINTIME |          LOGOUTTIME |
|--------|--------------------|---------------------|
|      1 | 26/04/2013 8:05:17 |              (null) |
|      2 | 26/04/2013 8:05:17 | 26/04/2013 17:28:47 |
|      3 |             (null) | 26/04/2013 17:32:24 |

在这里拉小提琴。

于 2013-10-18T04:05:29.453 回答