Sql查询:选择最新的行

时间:2014-04-07 07:46:43

标签: sql postgresql join

我有两张这样的表:

表信息:

4 columns:
-mmsi (pk)
-name
-type

和table position_history

4 columns:
-mmsi (fk)
-latitude
-longitude
-timestamp (//datatype: timestamp without timezone)

position_history示例:

-----mmsi----latitude-----longitude------timestamp------
-----------| -----------|-------------|----------------
    1001   |   34.3454  |     123.343 | 2014-04-07 03:37:00
    1001   |   24.5443  |     123.343 | 2014-03-07 14:23:00
    1001   |   14.1049  |     123.343 | 2014-02-07 18:12:00
    1001   |   54.2355  |     123.343 | 2014-01-07 02:00:00
    1002   |   34.3454  |     123.343 | 2014-04-07 03:37:00
    1002   |   24.3454  |     123.343 | 2014-03-07 03:44:00
    1002   |   14.3454  |     123.343 | 2014-02-07 15:37:00
    1002   |   54.3454  |     123.343 | 2014-01-07 12:32:00

和信息:

 -----mmsi------name---------type--------
-----------| -----------|----------------
    1001   |   dsg      |     abc
    1002   |   cvv      |     xyz

如何查询返回结果?

mmsi-----name-----type------latitude-----longitude------update_time
1001     dsg       abc       34.3454      123.343      2014-04-07 03:37:00
1002     cvv       xyz       34.3454      123.343      2014-04-07 03:37:00

2 个答案:

答案 0 :(得分:0)

简单的内部联接将会这样做

select p.mmsi, i.name, i.type, p.latitude, p.longitude, max(p.update_time)
from position_history p inner join info i
         on p.mmsi=i.mmsi
group by p.mmsi

OR

select p.mmsi, i.name, i.type, p.latitude, 
         p.longitude, p.update_time
from position_history p inner join info i
         on p.mmsi=i.mmsi
where p.update_time in (select max(update_time) from table1
                         group by mmsi)

fiddle

答案 1 :(得分:0)

select *
from info 
  join (
      select mmsi,
             latitude,
             longitude,
             timestamp,
             row_number() over (partition by mmsi order by timestamp desc) as rn
      from position_history
  ) ph on ph.mmsi = info.mmsi and ph.rn = 1;

或使用可能更快一点的distinct on

select *
from info 
  join (
      select distinct on (mmsi)
             mmsi,
             latitude,
             longitude,
             timestamp
      from position_history
      order by mmsi, timestamp desc
  ) ph on ph.mmsi = info.mmsi;

btw:timestamp是一个可怕的名字。一个是因为它也是一个保留字,其次是因为它没有记录列所包含的内容:a"开始日期"? "结束日期"? a"截止日期"? a"注册日期"?