我想将一个字段与前一行和下一行连接起来。例如,如果我有这个:
|ID|word|
|0 |Hi! |
|1 |How |
|2 |Are |
|3 |You |
我想创建一个存储过程,输入'before'和'after',表示当前行的前一行和下一行应该使用多少行。 例如,如果我们在= 1之前和之后= 1那么我们将得到这个
|ID|word |
|0 |Hi! How |
|1 |Hi! How Are|
|2 |How Are You|
|3 |Are You |
如果我们之前= 2且之后= 1,那么我们将得到这个
|ID|word |
|0 |Hi! How |
|1 |Hi! How Are |
|2 |Hi! How Are You|
|3 |How Are You |
提前致谢
答案 0 :(得分: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
答案 1 :(得分:0)
SELECT Columnname +''+(
SELECT TOP 1 Myt2.Columnname
FROM table1 Myt2
在哪里Myt2.ColumnID< t1.ColumnID
订购
ColumnID的
)
FROM table1 Myt1
订购
Myt1.ColumnID
此代码段适用于2个级别... :)仍然不是完整的答案。它可能有助于你达到第n级。