来自这样的表格
----------------------------------
| User | TimeStamp | Kind|
----------------------------------
| bob |2015-01-19 03:14:16| err |
| bob |2015-01-20 02:07:18| ok | <-- from here |
| bob |2015-01-21 12:07:18| err | |
| bob |2015-01-22 12:08:26| ok | |
| bob |2015-01-22 13:40:04| err | <-- to here |
| bob |2015-01-23 20:07:00| ok |
| tom |2015-01-19 03:14:16| err |
| tom |2015-01-20 02:07:18| ok | <-- from here|
| tom |2015-01-22 13:40:04| err | <-- to here |
| tom |2015-01-23 20:07:00| ok |
如何从第一个行获取Kind = ok 到 last 且Kind = 错误
预期结果:
----------------------------------
| User | TimeStamp | Kind|
----------------------------------
| bob |2015-01-20 02:07:18| ok |
| bob |2015-01-21 12:07:18| err |
| bob |2015-01-22 12:08:26| ok |
| bob |2015-01-22 13:40:04| err |
| tom |2015-01-20 02:07:18| ok |
| tom |2015-01-22 13:40:04| err |
表中没有唯一的ID,但是时间戳是有序的
编辑:可以有多个用户
答案 0 :(得分:2)
您可以使用以下查询:
SELECT User, TimeStamp, Kind
FROM mytable
WHERE TimeStamp BETWEEN (SELECT MIN(TimeStamp)
FROM mytable
WHERE Kind = 'ok')
AND
(SELECT MAX(TimeStamp)
FROM mytable
WHERE Kind = 'err')
如果要将上述查询应用于涉及多个User
值的数据,则必须在子查询中使用相关性,以便获得MIN
和{{1每个用户 :
MAX
或者,您可以使用SELECT User, TimeStamp, Kind
FROM mytable AS t1
WHERE TimeStamp BETWEEN (SELECT MIN(t2.TimeStamp)
FROM mytable AS t2
WHERE t1.User = t2.User AND t2.Kind = 'ok')
AND
(SELECT MAX(t3.TimeStamp)
FROM mytable AS t3
WHERE t1.User = t3.User AND t3.Kind = 'err')
:
INNER JOIN