sql ID 按顺序串联在单独的列中,如 运行 总计
sql Id concatenation in sequence in a separate column like running total
我需要 运行 ID 串联,就像 运行 余额或总计一样..
将之前的 ID 逐行连接到当前的 Id,如图所示
查询是
with relation (Id, [orderSequence])
as
(
select Id,cast(Id as varchar(20))
from [ACChartofAccount]
union all
select p.Id, cast(Cast(r.Id as varchar) + ',' + cast(p.Id as varchar) as varchar(20))
from [ACChartofAccount] p
inner join relation r on p.ParentId = r.Id
)
select Id,orderSequence
from relation
order by orderSequence
您可以使用下面的查询来获得上面的结果。
DECLARE @Table TABLE(ID VARCHAR(10));
INSERT INTO @table(ID) VALUES ('320'),(332),(333),(334),(335);
SELECT mt.ID,
STUFF((
SELECT ', ' + ID
FROM @table t
WHERE t.ID <= mt.ID
FOR XML PATH('')), 1, 2, '') AS oldersequence
FROM @table mt
ORDER BY ID
我需要 运行 ID 串联,就像 运行 余额或总计一样.. 将之前的 ID 逐行连接到当前的 Id,如图所示
查询是
with relation (Id, [orderSequence])
as
(
select Id,cast(Id as varchar(20))
from [ACChartofAccount]
union all
select p.Id, cast(Cast(r.Id as varchar) + ',' + cast(p.Id as varchar) as varchar(20))
from [ACChartofAccount] p
inner join relation r on p.ParentId = r.Id
)
select Id,orderSequence
from relation
order by orderSequence
您可以使用下面的查询来获得上面的结果。
DECLARE @Table TABLE(ID VARCHAR(10));
INSERT INTO @table(ID) VALUES ('320'),(332),(333),(334),(335);
SELECT mt.ID,
STUFF((
SELECT ', ' + ID
FROM @table t
WHERE t.ID <= mt.ID
FOR XML PATH('')), 1, 2, '') AS oldersequence
FROM @table mt
ORDER BY ID