2016-03-30 66 views
0

我需要在運行標識級聯就像運行平衡或總.. 串聯以前的ID,以當前ID行明智仿如顯示在畫面SQL ID串聯喜歡跑步總

enter image description here

查詢

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 
+1

您正在使用哪些DBMS? –

+2

沒有模式,它是非常不清楚的。無論如何檢查** [DEMO](http://rextester.com/RKSS5575)** – lad2025

+0

@a_horse_with_no_name我猜SQL Server基於SSMS screenshoot :) – lad2025

回答

2

您可以使用下面的查詢來獲得上述結果。

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 
+0

感謝Gordon Linoff的格式化。我是新來堆棧溢出,所以我不知道如何做格式。 – Ali1320