TSQL查询
Accounts with Different Times of transaction done
我需要帮助来找出一种仅提取当前行和下一行之间的txn_time
差异小于5分钟的记录的方法。txn_time
已排序。
查看所附图像,仅应显示行1,2,3,6,7,8,因为每行之间的时间差在5分钟以内。
任何想法都会有所帮助。
样本数据:
rowno txn_Date_Time txn_time accountNo
1 2017-10-31 11:50:47.0000000 98989898
2 2017-10-31 11:52:23.0000000 98989898
3 2017-10-31 11:52:23.0000000 98989898
4 2017-10-31 11:59:03.0000000 98989898
5 2017-10-31 12:05:13.0000000 98989898
6 2017-10-31 12:41:06.0000000 98989898
7 2017-10-31 12:42:44.0000000 98989898
8 2017-10-31 12:44:02.0000000 98989898
9 2017-10-31 15:23:19.0000000 98989898
10 2017-10-31 16:19:17.0000000 98989898
最佳答案
在SQL Server 2012+中,使用LEAD
和LAG
函数而不是自联接效率更高。
WITH
CTE
AS
(
SELECT
rowno
,txn_Date_Time
,txn_time
,accountNo
,LEAD(txn_time) OVER (PARTITION BY accountNo ORDER BY txn_time, rowno) AS next_time
,LAG(txn_time) OVER (PARTITION BY accountNo ORDER BY txn_time, rowno) AS prev_time
FROM T
)
SELECT
rowno
,txn_Date_Time
,txn_time
,accountNo
FROM CTE
WHERE
DATEDIFF(second, prev_time, txn_time) < 5 * 60
OR
DATEDIFF(second, txn_time, next_time) < 5 * 60
ORDER BY txn_time, rowno;
关于sql - 仅获取当前行与下一行之间的时差小于5分钟的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47169295/