从另一个表加入DateTime和Latest Value

时间:2013-08-16 06:44:23

标签: sql sql-server

我有一个小型数据库,每天记录来自天气参数的数据。这是Microsoft SQL Server 2008快速数据库

我的表格如下:

station (id, name, position)
reading (station_id, timestamp, value) 
--station_id is the foreign key to id in station table

我想加入他们并获得如下结果:

id      | name    | value  | time
--------+---------+-------------------------
0       | lake    | 73     |2013/08/16 02:00
1       | pier    | 72     |2013/08/16 02:00
2       | gate    | 81     |2013/08/16 02:00

查看Join to only the "latest" record with t-sql之类的问题,我只能从第一个表中获取一行,并且使用Join two tables, only use latest value of right table,我只能从第二个表中获得最大时间。

如何获得我想要的输出?

2 个答案:

答案 0 :(得分:2)

可以使用子查询

完成
SELECT  s.id,
        s.name,
        r.value,
        r.timestamp

FROM    station as s
        INNER JOIN reading as r
        on s.id = r.station_id

WHERE   r.timestamp = (

    SELECT max(timestamp)
    FROM reading
    where reading.station_id = s.station_id

)

答案 1 :(得分:1)

SELECT STATION.ID,STATION.Name,T2.timestamp,T2.Value

FROM STATION
LEFT JOIN 
(
  SELECT station_id,timestamp, value
  FROM
  (
  SELECT station_id,timestamp, value, 
         ROW_NUMBER() OVER (PARTITION BY station_id ORDER BY timestamp DESC) as rn
  FROM reading
  ) as T1 
  WHERE RN=1
) as T2 on STATION.ID=T2.station_id
相关问题