SQL获取一个时间范围内的所有值-以及之前的值

时间:2019-03-30 23:23:48

标签: sql sql-server

我有一个表,其中每个ActorId都有一个Value,但是Value会随着时间变化,我们会跟踪这些值的所有变化。

示例:

Id  ActorId     Value   Timestamp
--------------------------------
1   5           10      2019-01-05
2   8           8       2019-01-07
3   8           5       2019-01-08
4   5           15      2019-01-11
5   3           12      2019-01-11
6   3           7       2019-01-12
7   3           14      2019-01-14
[...]

如果我们将所有内容都加载到内存中,那么很容易检查每个Actor在任何时候的值是什么(或者如果没有,则为 null / undefined )在查询日期之前设置)。实际上,我实际上需要将所有这些数据发送到浏览器,并在JavaScript中完成。

问题在于整个表将变得非常大。分别在唯一的ActorIds 和每个ActorId的值更改中。

通常,我只需要选择相对较少的ActorId,并且时间很短,例如两个月。

我可以做类似的事情:

SELECT *
FROM [ActorValue]
WHERE 
    ActorId IN (5, 8, 12, [...])
    AND Timestamp >= '2019-02-01' 
    AND Timestamp <= '2019-04-01'

并将这些结果发送到JavaScript进行进一步处理。

问题在于,我也需要在周期开始时输入值 。因此,对于每个ActorId,我都需要日期范围内的值,并且在此范围内一个值更改

在不将所有值更改都加载到内存的情况下解决此问题的最佳方法是什么。

所以我在理论上寻找的是这样的东西:

 AND Timestamp >= '2019-02-01' -- plus the entry before this date, grouped by ActorId

2 个答案:

答案 0 :(得分:1)

我认为可以通过在NOT EXISTS子句中添加更多条件来解决此问题。记录属于分析间隔,或者是有关参与者的分析时间段开始之前的最新记录。可以使用SELECT * FROM [ActorValue] a WHERE ActorId IN (5, 8, 12, [...]) AND ( ( Timestamp >= '2019-02-01' AND Timestamp <= '2019-04-01' ) OR ( Timestamp < '2019-02-01' AND NOT EXISTS ( SELECT 1 FROM [ActorValue] a1 WHERE a1.ActorId = a.ActorId AND a1.Timestamp < '2019-02-01' AND a1.Timestamp > a.Timestamp ) ) 条件和相关子查询来表达后一个条件。

尝试:

{{1}}

答案 1 :(得分:1)

我只会使用do { counter++; System.out.println(trans.length); System.out.println(counter); System.out.println("How many CD/s would you like to buy?"); cd = scan.nextInt(); double cd_sales = sales(cd, CD_PRICE, HST); System.out.println("How many DVD/s would you like to buy?"); dvd = scan.nextInt(); double dvd_sales = sales(dvd, DVD_PRICE, HST); double cart = cd + dvd; double total_sales; if (cart > 7) { total_sales = total(cd_sales, dvd_sales, discount); System.out.println(total_sales); counter++; } else if (cart > 14) { total_sales = total(cd_sales, dvd_sales, sup_discount); System.out.println(total_sales); counter++; } else { total_sales = cd_sales + dvd_sales; System.out.println(total_sales); counter++; } for (int i=0;i<trans.length;i++){ trans[0]=total_sales; System.out.println(trans.length); double[] newtrans = Arrays.copyOf(trans, counter+1); newtrans[counter]=trans[0]; System.out.println(Arrays.toString(newtrans)); } //double sum=Arrays.stream(trans).sum(); System.out.println("New Customer? Y/N"); ans = scan.next().charAt(0); } while ((ans == 'Y') && (ans != 'N') || (ans == 'y') && (ans != 'n'));

lead()