0

假设我们有下表:

id  |  name  |  time
 1  |  Test  |  10
 2  |  Test  |  24
 3  |  Test  |  30
 4  |  ABCD  |  10
 5  |  ABCD  |  89
 6  |  EFGH  |  5
 7  |  WXYZ  |  5
 8  |  WXYZ  |  7
 9  |  Test  |  10
10  |  Test  |  24
11  |  EFGH  |  7

我想通过查询获得以下输出:

name  |  min_time  |  max_time
Test  |        10  |        30
ABCD  |        10  |        89
EFGH  |         5  |         5
WXYZ  |         5  |         7
Test  |        10  |        24
EFGH  |         7  |         7

类似于 GROUP BY 但有历史的东西......

SELECT name, MIN(time), MAX(time)
FROM table
GROUP BY name
ODER BY id ASC

使用此查询,它只会将每个名称组合在一起......但我希望它只在相同名称在行之后或之前进行分组。

有人知道该怎么做吗?

4

1 回答 1

1

这应该这样做:

select name, min(time), max(time)
from (
select
name, 
time,
@group_num := if(@name != name, @group_num + 1, @group_num) AS group_number,
@name := name
from yourTable
, (select @group_num := 1, @name := NULL) variables
order by id
) sq
group by group_number
于 2013-09-13T22:33:37.983 回答