按存储在另一个 Table 中的日期查找以前的记录
Find Previous record by date stored in another Table
所以我有 2 个表,一个记录一天结束时收银机上的现金以及第二天还剩多少钱,另一个记录基本的日期记录(表不能连接)所有看起来像这样的:
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 应该 return 这个
的声明
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,所以最终目的是知道当天卖了多少。
一天结束时的现金减去前一天留在收银机上的现金应该告诉我这一点。提前致谢。
请尝试以下操作 - 希望对您有所帮助:
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
所以我有 2 个表,一个记录一天结束时收银机上的现金以及第二天还剩多少钱,另一个记录基本的日期记录(表不能连接)所有看起来像这样的:
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 应该 return 这个
的声明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,所以最终目的是知道当天卖了多少。 一天结束时的现金减去前一天留在收银机上的现金应该告诉我这一点。提前致谢。
请尝试以下操作 - 希望对您有所帮助:
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