我需要提供从单个表中获取下一个/上一个记录的ID。有意义的表字段是Id和Date。数据示例:
Date Id
2015/01/15 3
2015/01/15 5
2015/01/15 7
2015/01/16 4
2015/01/16 6
2015/01/16 8
如您所见,记录按日期排序,然后是Id。如果我的当前记录是Id = 5的记录,则查询应该为下一条记录返回7,为之前的3返回3。这意味着查询将接收Id参数,并返回相应的结果
有没有人有任何想法?我更喜欢一种常见的SQL方法,而不是特定于特定的数据库系统。
答案 0 :(得分:2)
DECLARE @table table
(
Date Date,
Id int
)
INSERT @table VALUES
('2015/01/15', 3),
('2015/01/15', 5),
('2015/01/15', 7),
('2015/01/16', 4),
('2015/01/16', 6),
('2015/01/16', 8)
SELECT
*,
(SELECT TOP 1 Id FROM @table WHERE [Date] < [current].[Date] OR ([Date] = [current].[Date] AND Id < [current].Id) ORDER BY [Date] DESC, Id DESC) AS PreviousId,
(SELECT TOP 1 Id FROM @table WHERE [Date] > [current].[Date] OR ([Date] = [current].[Date] AND Id > [current].Id) ORDER BY [Date], Id) AS NextId
FROM
@table [current]
使用子查询应该有效,但Id对于同一日期应该是唯一的
答案 1 :(得分:0)
如果您使用的是SQL Server 2012,则可以使用LAG
和LEAD
等功能:
DECLARE @table table
(
Date Date,
Id int
)
INSERT @table VALUES
('2015/01/15', 3),
('2015/01/15', 5),
('2015/01/15', 7),
('2015/01/16', 4),
('2015/01/16', 6),
('2015/01/16', 8)
;with cte as
(
select
[Date],
Id,
LAG(Id, 1, 0) over(order by [date]) previousId,
LEAD(Id, 1, 0) over(order by [date]) nextId
from @table
)
select * from cte where id = 5