gpt4 book ai didi

sql - 查找不连续的用户记录

转载 作者:行者123 更新时间:2023-12-03 01:35:29 25 4
gpt4 key购买 nike

我无法弄清楚如何启动此查询。

我有一个包含以下列和数据的表格:

User   BeginMile EndMile
1 1 5
1 5 6
1 6 20
1 20 25
1 25 29
2 1 9
2 15 20
3 1 2
3 6 10
3 10 12

我需要首先找到每个用户从上一条记录的 EndMile 到下一条记录的 BeginMile 之间的差距。然后,我需要返回每个用户出现间隙之前和之后的记录。

在前面的数据示例中,我希望返回以下内容:

User   PrevBeginMile   PrevEndMile    AfterBeginMile AfterEndMile   Gap
2 1 9 15 20 6
3 1 2 6 10 4

如何做到这一点?

最佳答案

考虑到您使用的是 SQL 2005,这应该可行:

DECLARE @Runners TABLE (Id INT, BeginMile INT, EndMile INT)

INSERT INTO @Runners VALUES (1,1,5)
INSERT INTO @Runners VALUES (1,5,6)
INSERT INTO @Runners VALUES (1,6,20)
INSERT INTO @Runners VALUES (1,20,25)
INSERT INTO @Runners VALUES (1,25,29)
INSERT INTO @Runners VALUES (2,1,9)
INSERT INTO @Runners VALUES (2,15,20)
INSERT INTO @Runners VALUES (3,1,2)
INSERT INTO @Runners VALUES (3,6,10)
INSERT INTO @Runners VALUES (3,10,12)

WITH OrderedUsers AS (
SELECT *
, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY BeginMile) RowNum
FROM @Runners
)

SELECT a.Id [User]
, a.BeginMile PrevBeginMile
, a.EndMile PrevEndMile
, b.BeginMile AfterBeginMile
, b.EndMile AfterEndMile
, b.BeginMile - a.EndMile Gap
FROM OrderedUsers a
JOIN OrderedUsers b
ON a.Id = b.Id
AND a.EndMile <> b.BeginMile
AND a.RowNum = b.RowNum - 1

关于sql - 查找不连续的用户记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6626567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com