选择某个时间戳之前的最新行

Selecting the most recent row before a certain timestamp

我有一个像这样的 table 叫做 tt

ID|Name|Date|Value|
------------------------------------
0|  S1| 2017-03-05 00:00:00|    1.5|
1|  S1| 2017-04-05 00:00:00|    1.2|
2|  S2| 2017-04-06 00:00:00|    1.2|
3|  S3| 2017-04-07 00:00:00|    1.1|
4|  S3| 2017-05-07 00:00:00|    1.2|

我需要 select 时间最长的行 每个 Name< theTime

theTime 只是一个带有时间戳的变量。在示例中,您可以对日期字符串进行硬编码,例如< DATE '2017-05-01' 稍后我将使用另一种语言以编程方式注入变量的值

我很难弄清楚该怎么做...有人知道吗?

此外,我想知道如何 select 我上面描述的但仅限于特定的 name,例如name='S3'

如果hsqldb真的支持就好了row_number():

select t.*
from (select tt.*,
             row_number() over (partition by name order by date desc) as seqnum
      from tt
      where  . . .
     ) t
where seqnum = 1;

缺少那个,使用 group byjoin:

select tt.*
from tt join
     (select name, max(date) as maxd
      from tt
      where date < THETIME
      group by name
     ) ttn
     on tt.name = ttn.name and tt.date = ttn.maxd;

注意:如果给定名称的最大日期重复,这将 return 重复。

where 对您的时间戳有限制。