如何根据选定的行获取上一行和下一行?

时间:2016-12-27 10:49:39

标签: sql-server tsql asp.net-mvc-4 sql-server-2012

我正在尝试获取所选行的上一行和下一行的确切 T-SQL语句。这是下面给出的表格。

表名: MyExTab

ID      Name     Address       Age    Nationality
------  -------  -----------   -----  -----------
1160    Kate     New Jersey    28     American
1161    Kelly    Connecticut   32     American
1162    Jenny    New York      30     American
1163    Heather  New York      29     American
1164    Ashley   Pennsylvania  29     American

如果我想使用代表行的 ID = 1162 查询行

ID      Name     Address       Age    Nationality
------  -------  -----------   -----  -----------
1162    Jenny    New York      30     American

它应该只返回基于所选行ID的上一行和下一行的两行,如下所示。

ID      Name     Address       Age    Nationality
------  -------  -----------   -----  -----------
1161    Kelly    Connecticut   32     American
1163    Heather  New York      29     American

请给予帮助。感谢

4 个答案:

答案 0 :(得分:5)

尝试这样

DECLARE @tbl TABLE(ID INT,Name VARCHAR(100));
INSERT INTO @tbl VALUES
 (1160,'Kate')
,(1161,'Kelly')
,(1162,'Jenny')
,(1163,'Heather')
,(1164,'Ashley');

DECLARE @id INT=1162;

查询将查找给定参数的最小的 最小的 ID

SELECT * 
FROM @tbl AS t
WHERE ID = (SELECT MIN(x.ID) FROM @tbl AS x WHERE x.ID>@id)
   OR ID = (SELECT MAX(x.ID) FROM @tbl AS x WHERE x.ID<@id)

答案 1 :(得分:1)

;with cte
as
(
select *,
lag(id) over (order by id) as pr,lead(id) over (order by id) as nr
 from @tbl
 )
select * from cte
where id  = (select pr from cte where id=1162)
or id=(select nr from cte where id=1162)

针对所有值进行了更新:可能效率不高

input

使用shungo的样本数据

答案 2 :(得分:1)

您可以尝试这种方式(类似于@TheGameiswar)。如果您使用 sql-server-2012 + ,那么您可以使用LAG()LEAD()来获取上一个和下一个记录。

;WITH CTE
AS
(
    SELECT *,
        LAG(ID) OVER (ORDER BY ID)  AS PREV_RWO,
        LEAD(ID) OVER (ORDER BY ID) AS NEXT_ROW
    FROM    MyExTab
)

SELECT  T.*
FROM    CTE AS  C
INNER JOIN  MyExTab AS  T   ON  T.ID = C.PREV_RWO
                            OR  T.ID = C.NEXT_ROW
WHERE   C.ID = 1162 

答案 3 :(得分:0)

你试过这个: -

declare  @id int
set @id = 1162    
select * from tableName
where id in ( @id - 1 , @id + 1)