我无法弄清楚如何开始此查询。
我有一个包含以下列和数据的表:
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
如何做到这一点?
答案 0 :(得分:3)
考虑到你在使用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
答案 1 :(得分:0)
除了使用RowNumber()[如在其他答案中],您可以使用...
SELECT
[current].User,
[current].BeginMile AS [PrevBeginMile],
[current].EndMile AS [PrevEndMile],
[next].BeginMile AS [AfterBeginMile],
[next].EndMile AS [AfterEndMile],
[next].BeginMile - [current].EndMile AS [Gap]
FROM
myTable AS [current]
CROSS APPLY
(SELECT TOP 1 * FROM myTable WHERE user = [current].User AND BeginMile > [current].BeginMile ORDER BY BeginMile ASC) AS [next]
WHERE
[current].EndMile <> [next].BeginMile
或者可能......
FROM
myTable AS [current]
INNER JOIN
myTable AS [next]
ON [next].BeginMile != [current].EndMile
AND [next].BeginMile = (
SELECT
MIN(BeginMile)
FROM
myTable
WHERE
user = [current].User
AND BeginMile > [current].BeginMile
)
答案 2 :(得分:0)
怎么样
WITH acte(user,beginmile,endmile) AS
(
SELECT user,start,end
ROW_NUMBER() OVER(PARTITION BY user ORDER BY START ASC) rownum
FROM mytable
)
SELECT base.user,base.beginmile,base.endmile,base.BeginMile - lead.EndMile Gap
FROM acte base
LEFT JOIN acte lead on base.id=lead.id AND base.rownum=lead.rownum-1
WHERE base.BeginMile - lead.EndMile > 0