1

我有一张有一堆记录的表:

userID    testID    value    time
1         1001      2        2009-09-05 06:25:00
1         1001      4        2009-09-05 07:25:00
1         1001      2        2009-09-05 03:25:00
1         1002      5        2009-09-05 06:25:00
1         1002      6        2009-09-05 07:25:00
1         1002      4        2009-09-05 03:25:00

用户在时间 x 进入。我想在入学的前 X 小时内查询每个测试的最新值。IE 如果他在 3:25 进入并且我想要 3 小时内的最新值,我想要返回

1         1001      2        2009-09-05 07:25:00
1         1002      5        2009-09-05 07:25:00

我不确定解决这个问题的最佳方法,但这是我迄今为止尝试过的:

SELECT testID, value from table WHERE userID = 1 and 
    time <= timestamp 'enter_time' + INTERVAL '3 HOURS' as u INNER JOIN 
    (SELECT testID, max(time) as time from table WHERE time <= timestamp 
    'enter_time' + INTERVAL '3 HOURS' GROUP BY testID) as q 
    on u.itemid = q.itemid AND u.time = q.time

我收到了一个语法错误,但代码似乎是正确的。有人可以帮帮我吗?

谢谢!

4

1 回答 1

0

您需要将第一个查询包装在括号中。

(SELECT testID, value from table WHERE userID = 1 and 
    time <= timestamp 'enter_time' + INTERVAL '3 HOURS') as u INNER JOIN 
    (SELECT testID, max(time) as time from table WHERE time <= timestamp 
    'enter_time' + INTERVAL '3 HOURS' GROUP BY testID) as q 
    on u.itemid = q.itemid AND u.time = q.time
于 2013-08-02T15:52:30.553 回答