2013-08-02 44 views
1

内我有一个表一堆纪录: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小时内查询每个测试的最新值。也就是说,如果他在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 

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

谢谢!

+0

你得到了什么错误,以及RBDMS是什么? MySQL的?甲骨文? –

+0

我在postgresql上。错误只是“AS上或附近的语法错误”,其中AS是ASU部分。 – xhassassin

回答

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