如何从分组行的第一行/最后一行获取值?

时间:2013-01-01 17:32:16

标签: mysql sql aggregate-functions

我有一个列表的数据结构:

 from | to | connection_id | date
------+----+---------------+------
  A   | B  | 1             | some
  B   | C  | 1             | dates
  B   | D  | 2             | I can
  D   | E  | 2             | sort
  E   | C  | 2             | by

我想通过connection_id列对数据进行分组,我想要的结果是:

 from | to | connection_id
------+----+---------------
  A   | C  | 1            
  B   | C  | 2            

所以我希望分组行中第一行的from-value和分组行中最后一行的to-value。要获取最后一行和第一行,可以使用日期列进行排序。如何从分组行的第一行/最后一行中获取一个值?

编辑:澄清:对于每个connection_id,我希望来自具有最低日期值的行的from-value和来自具有最高日期值的行的to-value。

2 个答案:

答案 0 :(得分:3)

如果行可以按date字段排序,我想你可以使用它:

select t1.`from`, t2.`to`, mm.connection_id
from (
  select connection_id, min(`date`) as minDate, max(`date`) as maxDate
  from trains
  group by connection_id) mm
  inner join trains t1 on mm.connection_id=t1.connection_id and t1.`date`=mm.minDate
  inner join trains t2 on mm.connection_id=t2.connection_id and t2.`date`=mm.maxDate

这里我选择每个connection_id的第一行和最后一行,从第一行开始from列,从最后一列开始to列。或者你也可以使用这个技巧:

select
  SUBSTRING_INDEX(GROUP_CONCAT(`from` ORDER BY `date`), ',', 1 ) as `from`,
  SUBSTRING_INDEX(GROUP_CONCAT(`to` ORDER BY `date`), ',', -1 ) as `to`,
  connection_id
from trains
group by connection_id

答案 1 :(得分:1)

您可以使用order by在两个select上尝试union。如下所示:

Select * from yourtable 
group by connection_id
order by [from] desc limit 1
union
select * from yourtable
group by connection_id 
order by [to] asc limit 1