按日期存储在另一个表中查找上一条记录

时间:2015-01-08 22:19:56

标签: sql-server

所以我有两张桌子,一张在当天结束时保留现金登记册上的现金记录以及第二天剩余多少钱,另一张记录基本记录日期(表格无法加入)所有看起来像这样:

    RegistersTable
------------------
Register_ID| DATE
5          | 02/02/2012
8          | 04/02/2012
1          | 10/02/2012

CashTable
----------------
Register_ID|CashEOD|CashFND
8          |3235   |325
5          |6843   |435
1          |1236   |1953

所以我试图得到的是一个应该返回此

的select语句
RegisterID|      DATE|CashEOD|PrevCashFND
1         |10/02/2012|1236   |325
8         |04/02/2012|3235   |435
5         |02/02/2012|6843   |0/Null 

从CashTable上的RegisterID开始,在RegistersTable的DATE找到之前的RegisterID,获取之前的CashFND,这样最终的目标就是知道当天有多少被选中。 现金结束日减去前一天登记册上留下的现金应该告诉我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

请尝试以下操作 - 我希望它有所帮助:

SELECT
    D.RegisterID,
    D.[DATE],
    CashTable.CashEOD,
    CashTable_Prev.CashFND AS PrevCashFND
FROM
    (
        SELECT 
            A.RegisterID,
            A.[DATE],
            B.RegisterID AS PrevID
        FROM
            RegistersTable A
            INNER JOIN RegistersTable B ON A.RegisterID <> B.RegisterID AND A.[DATE] > B.[DATE]
            INNER JOIN
            (
                SELECT 
                    _innA.RegisterID,
                    _innB.RegisterID As PrevID,
                    MIN(_innA.[DATE] - _innB.[DATE]) AS MinDateDiff
                FROM
                    RegistersTable _innA
                    INNER JOIN RegistersTable _innB ON _innA.RegisterID <> _innB.RegisterID AND _innA.[DATE] > _innB.[DATE]
                GROUP BY
                    _innA.RegisterID,
                    _innB.RegisterID
            ) C
                ON A.RegisterID = C.RegisterID AND B.RegisterID = C.PrevID AND (A.[DATE] - B.[DATE]) = C.MinDateDiff
    ) AS D
    INNER JOIN CashTable 
        ON CashTable.Register_ID = D.RegisterID
    INNER JOIN CashTable AS CashTable_Prev
        ON CashTable_Prev.Register_ID = D.PrevID