0

我有一个带有火车的表的数据结构:

 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            

所以我想从分组行中的第一行获取从值,从分组行的最后一行获取到值。要获取最后一行和第一行,有要排序的日期列。如何从分组行中的第一行/最后一行获取一个值?

编辑:澄清:对于每个connection_id,我希望从具有最低日期值的行中获取起始值,并从具有最高日期值的行中获取到值。

4

2 回答 2

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_idfrom的第一行和最后一行,从第一行取列,从最后一行取列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
于 2013-01-01T17:45:53.727 回答
1

你可以试试order by两个selectunion如下所示:

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
于 2013-01-01T17:34:18.547 回答