SQL在时间间隔内选择记录

时间:2013-08-02 15:45:06

标签: sql

我有一张包含大量记录的表格:

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

(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