如何选择每个组中的第一个值

时间:2017-06-29 11:20:05

标签: mysql

mysql> create table t1(id int,level int,gap int);
mysql> insert into t1 values (1,6,50),(1,5,10),(2,5,10),(2,5,12),(3,8,10),
(3,8,2),(3,9,6),(3,9,4);

这两个命令可以创建如下表

mysql> select * from t1;
+------+-------+------+
| id   | level | gap  |
+------+-------+------+
|    1 |     6 |   50 |
|    1 |     5 |   10 |
|    2 |     5 |   10 |
|    2 |     5 |   12 |
|    3 |     8 |   10 |
|    3 |     8 |    2 |
|    3 |     9 |    6 |
|    3 |     9 |    4 |
+------+-------+------+
8 rows in set (0.00 sec)

我想在level最大时选择一条记录,但每个group by id的差距都很小。所以我认为这段代码对我有用

mysql> select id,max(level),first(gap) from (select * from t1 group by id,
level,gap) as tem group by id;

但是我发现mysql没有first函数。这是当前的解决方案。

select
  tt.id,tt.level,min(tt.gap) min_gap 
from (
  select * from t1 tt1
    where not exists(
      select 1 from t1 tt2 where tt1.id=tt2.id and tt1.level<tt2.level
    )
  ) tt
group by tt.id,tt.level;

它将提供正确答案,如

但有没有简洁的方法可以解决这个问题?

0 个答案:

没有答案