使用SQL有效地获取以前的值

时间:2017-05-26 11:08:04

标签: sql ms-access ms-access-2010

当我使用相当大的数据集时,我正在寻找一种更有效的方法来获取基于日期序列的先前值。我目前正在为每个值使用SELECT TOP 1子查询,但每次运行查询时都需要花费大量时间

示例数据:

TDate       Object    Price     Volume
18.05.2017  ObjectA     105      10
18.05.2017  ObjectB     110      10
18.05.2017  ObjectC     120      10
19.05.2017  ObjectA     100      12
19.05.2017  ObjectB     75       10
19.05.2017  ObjectD     33       10
22.05.2017  ObjectA     105      15
22.05.2017  ObjectB     80       10
22.05.2017  ObjectD     55       10

我的代码:

SELECT  TDate AS TodaysDate, Object, Price AS TodaysPrice, Volume AS   TodaysVolume,
( SELECT TOP 1 TDate
                              FROM Table1 AS P2
                              WHERE P2.Object = Table1.Object
                                AND P2.TDate < Table1.TDate
                              ORDER BY P2.TDate DESC ) As prevDate,
( SELECT TOP 1 Price
                              FROM Table1 AS P2
                              WHERE P2.Object = Table1.Object
                                AND P2.TDate < Table1.TDate
                              ORDER BY P2.TDate DESC ) As prevPrice,
( SELECT TOP 1 Volume
                              FROM Table1 AS P2
                              WHERE P2.Object = Table1.Object
                                AND P2.TDate < Table1.TDate
                              ORDER BY P2.TDate DESC ) As PrevVolume
FROM Table1

输出:

TodaysDate  Object  TodaysPrice TodaysVolume    prevDate    prevPrice   PrevVolume
18.05.2017  ObjectA     105     10          
18.05.2017  ObjectB     110     10          
18.05.2017  ObjectC     120     10          
19.05.2017  ObjectA     100     12              18.05.2017      105     10
19.05.2017  ObjectB     75      10              18.05.2017      110     10
19.05.2017  ObjectD     33      10          
22.05.2017  ObjectA     105     15              19.05.2017      100     12
22.05.2017  ObjectB     80      10              19.05.2017      75      10
22.05.2017  ObjectD     55      10              19.05.2017      33      10

输出是正确的,但我非常感谢两件事的输入;

1)有没有办法更有效地计算以前的日期和价值? (我正在使用Microsoft Access 2010)

2)如何直接在SQL代码中加入TodaysPrice和PrevPrice之间的价格差异?

提前感谢您的任何建议和意见!

1 个答案:

答案 0 :(得分:1)

您可以使用子查询

SELECT   TodaysDate, TodaysObject, TodaysPrice, TodaysVolume, Today.PrevDate,
    prev.Price  as PrevPrice, prev.Volume as PrevVolume
FROM (
    SELECT  TDate AS TodaysDate, Object as TodaysObject, Price AS TodaysPrice, Volume AS   TodaysVolume,
        Table1.Object, ( SELECT MAX(P2.TDate)
                              FROM Table1 AS P2
                              WHERE P2.Object = Table1.Object
                                AND P2.TDate < Table1.TDate ) As PrevDate
    FROM Table1) Today
    LEFT JOIN Table1 as Prev ON Today.TodaysObject= Prev.Object AND Today.PrevDate = Prev.TDate