你可以從「最後文件」這樣的任意值:
SELECT
D.DocumentID,
D.Reference,
LastDocumentID = R.DocumentID
FROM
dbo.Documents D
OUTER APPLY (
SELECT TOP 1 *
FROM dbo.Documents R
WHERE
D.Reference = R.Reference
AND R.DocumentID < D.DocumentID
ORDER BY R.DocumentID DESC
) R
;
雖然具有相同的邏輯,在一個子查詢WHERE
子句中計算剛剛列值類似的方法,這允許您從以前的文檔中拉出多個列,並演示OUTER APPLY
。如果您想要等效的INNER
連接(不包括之前沒有的行),請更改爲CROSS APPLY
。
僅供參考,以下是實現此目的的單值方法。你基本上把包含在OUTER APPLY
到括號中的查詢,並且只選擇一列:
SELECT
D.DocumentID,
D.Reference,
LastDocumentID = (
SELECT TOP 1 R.DocumentID
FROM dbo.Documents R
WHERE
D.Reference = R.Reference
AND R.DocumentID < D.DocumentID
ORDER BY R.DocumentID DESC
)
FROM
dbo.Documents D
;
或者,您也可以只使用Max
:
SELECT
D.DocumentID,
D.Reference,
LastDocumentID = (
SELECT Max(R.DocumentID)
FROM dbo.Documents R
WHERE
D.Reference = R.Reference
AND R.DocumentID < D.DocumentID
)
FROM
dbo.Documents D
;
如果你使用SQL Server 2012及以上,你可以用它的更高級的語法來實現窗口化功能:
SELECT
D.DocumentID,
D.Reference,
LastDocumentID = Max(D.DocumentID) OVER (
PARTITION BY D.Reference
ORDER BY D.DocumentID ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
)
FROM
dbo.Documents D
;
你試過了什麼? – 2015-02-23 20:55:26