插入包含前几行信息的新列
Insert new colum with previous rows information
我有这个table:
Id |Name |ParentId
1 |John |Null
2 |Oscar |1
3 |Peter |2
4 |Abbey |3
5 |Adrian |4
6 |Barbara |5
我想创建一个 select,它将给我一个新列,该列通过 parentId 获取先前的名称,以创建一个 listName(按 ParentID 排序)。
这个例子的最终结果是这样的:
Id |Name |ParentId | List
1 |John |Null | John
2 |Oscar |1 | John-Oscar
3 |Peter |2 | John-Oscar-Peter
4 |Abbey |3 | John-Oscar-Peter-Abbey
5 |Adrian |4 | John-Oscar-Peter-Abbey-Adrian
6 |Barbara |5 | John-Oscar-Peter-Abbey-Adrian-Barbara
感谢大家的帮助!
这与将列连接到行相同
select id,name,pid,
stuff((select '-'+name from yourtable n2 where n2.id<=n1.id for xml path('')),1,1,'') b
from yourtable n1
您可以使用递归 CTE 来产生所需的结果:
declare @t table (Id int, Name varchar(20), ParentId int)
insert @t values
( 1 ,'John' ,Null ),
( 2 ,'Oscar' ,1 ),
( 3 ,'Peter' ,2 ),
( 4 ,'Abbey' ,3 ),
( 5 ,'Adrian' ,4 ),
( 6 ,'Barbara' ,5 )
;with x as (
select *, cast(name as varchar(1000)) as list from @t where parentid is null
union all
select t.id, t.name, t.parentid, cast(x.list+'-'+t.name as varchar(1000)) from @t t join x on t.parentid = x.id
)
select * from x
当然,这也适用于多个根。
我有这个table:
Id |Name |ParentId
1 |John |Null
2 |Oscar |1
3 |Peter |2
4 |Abbey |3
5 |Adrian |4
6 |Barbara |5
我想创建一个 select,它将给我一个新列,该列通过 parentId 获取先前的名称,以创建一个 listName(按 ParentID 排序)。
这个例子的最终结果是这样的:
Id |Name |ParentId | List
1 |John |Null | John
2 |Oscar |1 | John-Oscar
3 |Peter |2 | John-Oscar-Peter
4 |Abbey |3 | John-Oscar-Peter-Abbey
5 |Adrian |4 | John-Oscar-Peter-Abbey-Adrian
6 |Barbara |5 | John-Oscar-Peter-Abbey-Adrian-Barbara
感谢大家的帮助!
这与将列连接到行相同
select id,name,pid,
stuff((select '-'+name from yourtable n2 where n2.id<=n1.id for xml path('')),1,1,'') b
from yourtable n1
您可以使用递归 CTE 来产生所需的结果:
declare @t table (Id int, Name varchar(20), ParentId int)
insert @t values
( 1 ,'John' ,Null ),
( 2 ,'Oscar' ,1 ),
( 3 ,'Peter' ,2 ),
( 4 ,'Abbey' ,3 ),
( 5 ,'Adrian' ,4 ),
( 6 ,'Barbara' ,5 )
;with x as (
select *, cast(name as varchar(1000)) as list from @t where parentid is null
union all
select t.id, t.name, t.parentid, cast(x.list+'-'+t.name as varchar(1000)) from @t t join x on t.parentid = x.id
)
select * from x
当然,这也适用于多个根。