2

我想将一个字段与前一行和下一行连接起来。例如,如果我有这个:

|ID|word|
|0 |Hi! |
|1 |How |
|2 |Are |
|3 |You |

我想创建一个带有输入“之前”和“之后”的存储过程,它们指示当前行的上一行和下一行应该使用多少行。例如,如果我们有 before=1 和 after=1 那么我们会得到这个

|ID|word       |
|0 |Hi! How    |
|1 |Hi! How Are|
|2 |How Are You|
|3 |Are You    |

如果我们有 before=2 和 after=1 那么我们会得到这个

|ID|word           |
|0 |Hi! How        |
|1 |Hi! How Are    |
|2 |Hi! How Are You|
|3 |How Are You    |

提前致谢

4

2 回答 2

2

检查这个: DECLARE @before TINYINT = 2 DECLARE @after TINYINT = 1

SELECT  ISNULL(( SELECT STUFF((SELECT   ISNULL(TblBefore.word, '') + ' '
                               FROM     Tbl TblBefore
                               WHERE    TblBefore.Id BETWEEN T.Id - @before AND T.Id
                                        - 1
                        FOR   XML PATH('') ,
                                  TYPE).value('.', 'varchar(max)'), 1, 0, '') AS ChildValues
               ), '') + T.Word + ' '
        + ISNULL(( SELECT   STUFF((SELECT   ISNULL(TblBefore.word, '') + ' '
                                   FROM     Tbl TblBefore
                                   WHERE    TblBefore.Id BETWEEN T.Id + 1 AND T.Id
                                            + @after
                            FOR   XML PATH('') ,
                                      TYPE).value('.', 'varchar(max)'), 1, 0,
                                  '') AS ChildValues
                 ), '')
FROM  Tbl T
于 2013-09-24T20:00:31.643 回答
0

SELECT Columnname + ' ' + ( SELECT TOP 1 Myt2.Columnname FROM table1 Myt2 WHERE Myt2.ColumnID < t1.ColumnID
ORDER BY ColumnID ) FROM table1 Myt1 ORDER BY Myt1.ColumnID

此代码片段适用于 2 个级别...:) 仍然不是完整的答案。它可能有助于让你达到第 n 级。

于 2013-09-24T10:30:20.583 回答