我一直试图在SQL Server中编写查询,这将帮助我获得用户的下一个操作时间作为上一条记录的操作结束。我如何查询以获取下一个操作的结束日期,而查询的最后一条记录将没有其他记录,那么我正在尝试获取sysdate
SELECT
UL.UL_US_ID,
UL_ACTION_TIME
FROM USER_LOG UL
JOIN USER_MAIN UM
ON UL.UL_US_ID = UM.US_ID
WHERE UL.UL_ACTION IN ('LI')
AND UM.US_UT_ID = '1'
AND CONVERT(varchar(10), UL.UL_ACTION_TIME, 111) = CONVERT(varchar(10), GETDATE(), 111)
ORDER BY ul.UL_US_ID, ul.UL_ACTION_TIME;
***Existing Data Sample***
+----------+-----------------+
| user | acton_time |
+----------+-----------------+
| hudhaifa | 8/27/2019 9:03 |
| hudhaifa | 8/27/2019 9:40 |
| hudhaifa | 8/27/2019 9:51 |
| hudhaifa | 8/27/2019 10:41 |
| hudhaifa | 8/27/2019 10:56 |
+----------+-----------------+
***Required Data Sample***
+----------+-----------------+-----------------+
| user | acton_time | action_end |
+----------+-----------------+-----------------+
| hudhaifa | 8/27/2019 9:03 | 8/27/2019 9:40 |
| hudhaifa | 8/27/2019 9:40 | 8/27/2019 9:51 |
| hudhaifa | 8/27/2019 9:51 | 8/27/2019 10:41 |
| hudhaifa | 8/27/2019 10:41 | 8/27/2019 10:56 |
| hudhaifa | 8/27/2019 10:56 | sysdate |
+----------+-----------------+-----------------+
答案 0 :(得分:1)
假定SQL Server(或任何支持解析功能的RDBMS)仅使用LEAD
函数:
SELECT user
, action_time
, LEAD(action_time, 1, CURRENT_TIMESTAMP) OVER (PARTITION BY user ORDER BY action_time ASC) AS action_end
FROM t