One easy way to do this is using OUTER APPLY
:
SELECT t1.CustomerID
, t1.TransType
, t2.[DateTime] AS DepositDate
, t1.[DateTime] AS WithdrawalDate
FROM t t1
OUTER APPLY
(
SELECT TOP 1 [DateTime]
FROM t t2
WHERE
t1.CustomerID = t2.CustomerID
AND
t2.[DateTime] < t1.[DateTime]
AND
TransType = 'Deposit'
ORDER BY [DateTime] DESC
)
WHERE t1.TransType = 'Withdrawal'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…