sql – 从使用(WHERE)条件选择的行中获取上一行和下一行

前端之家收集整理的这篇文章主要介绍了sql – 从使用(WHERE)条件选择的行中获取上一行和下一行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一张这样的桌子

例如,我有这样的声明:

my name is joseph and my father name is brian

此语句按此表分类

------------------------------
|      ID      |    word     |
------------------------------
|       1      |     my      |
|       2      |     name    |
|       3      |     is      |
|       4      |     joseph  |
|       5      |     and     |
|       6      |     my      |
|       7      |     father  |
|       8      |    name     |
|       9      |     is      |
|       10     |    brian    |
------------------------------

我想获得相同单词的上一个和下一个值

例如,我想获得“name”的上一个和下一个单词:

--------------------------
|   my    |  name  |  is |
--------------------------
|  father |  name  |  is |
--------------------------

我怎样才能做到这一点?

解决方法

您没有指定DBMS,因此以下是ANSI sql
select prev_word,word,next_word
from (
    select id,lag(word) over (order by id) as prev_word,lead(word) over (order by id) as next_word
    from words
) as t
where word = 'name';

sqlFiddle:http://sqlfiddle.com/#!12/7639e/1

猜你在找的MsSQL相关文章