3

我有一个小型数据库,其中包含每天记录的天气参数数据。这是一个 Microsoft SQL Server 2008 express 数据库

我的表格如下:

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两个表,只使用右表的最新值,我一直只能从第二个表中获得最大时间。

我怎样才能得到我想要的输出?

4

2 回答 2

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

)
于 2013-08-16T06:56:33.420 回答
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
于 2013-08-16T06:51:53.407 回答