accountid txnid txndate
1 176 2015-11-27 00:00:00
1 177 2015-12-27 00:00:00
472 202 2015-12-01 00:00:00
472 203 2015-12-10 00:00:00
我具有上述表格结构, 需要找到单个帐户ID的两个交易日期之间的日期差
预期输出
accountid txnid txndate diffdays_trans
1 176 2015-11-27 00:00:00 0
1 177 2015-12-27 00:00:00 30
472 202 2015-12-01 00:00:00 0
472 203 2015-12-10 00:00:00 10
由于txnid 176是第一笔交易,没有时差,因此帐户#1的txn 177在1个月后出现,因此时差为30天, 同样,对于帐户472,trans#202是第一笔交易,因此将是0天,而trans#203在10天后出现,因此天差是10
答案 0 :(得分:1)
要查找各个帐户ID的两次交易日期之间的差额:
DECLARE @TestTable TABLE (accountid INT, txnid INT, txndate DATETIME);
INSERT INTO @TestTable (accountid, txnid, txndate) VALUES
(1 , 176, '2015-11-27 00:00:00'),
(1 , 177, '2015-12-27 00:00:00'),
(472, 202, '2015-12-01 00:00:00'),
(472, 203, '2015-12-10 00:00:00');
SELECT accountid, txnid, txndate, ISNULL(DATEDIFF(DAY, NextDateTime, txndate), 0) AS [diffdays_trans]
FROM (
SELECT accountid, txnid, txndate,
LAG (txndate, 1) OVER (PARTITION BY accountid ORDER BY accountid) AS NextDateTime
FROM @TestTable
) AS Q
结果将为:
accountid txnid txndate diffdays_trans
-------------------------------------------------------------
1 176 2015-11-27 00:00:00.000 0
1 177 2015-12-27 00:00:00.000 30
472 202 2015-12-01 00:00:00.000 0
472 203 2015-12-10 00:00:00.000 9
答案 1 :(得分:1)
您可以使用线索功能获取下一个交易日期。
.vbhtml