Sqlserver
 sql >> база данни >  >> RDS >> Sqlserver

SQL Server за показване на дърво с данни в определен формат

Примерната таблица

create table so1 (Itemid varchar(100), Itemname varchar(100), Itemfatherid varchar(100))
insert so1 select
'itemA','theitemA',null union all select
'itemB','theitemB',null union all select
'itemC','theitemC','itemA' union all select
'itemD','theitemD','itemA' union all select
'itemE','theitemE','itemC' union all select
'itemF','theitemF','itemE' union all select
'itemG','theitemG','itemD'

Заявката

if OBJECT_ID('tempdb..#tmp') is not null drop table #tmp
;
create table #tmp (
    uniqueid uniqueidentifier not null,
    level int not null,
    itemid varchar(100) null,
    primary key clustered(uniqueid, level)
)
;with cte(level, itemid, parentid, uniqueid) as
(
    select 1, itemid, itemfatherid, NEWID()
    from so1
    where not exists (select * from so1 k where k.itemfatherid=so1.itemid)
    union all
    select cte.level+1, t.itemid, t.itemfatherid, cte.uniqueid
    from cte
    inner join so1 t on t.Itemid = cte.parentid
)
insert #tmp (uniqueid, level, itemid)
select uniqueid, level, itemid
from cte
option (maxrecursion 1000) -- as required
;
;with tmp as (
    select *, newlevel = ROW_NUMBER() over (partition by uniqueid order by level desc)
    from #tmp)
update tmp
set level = newlevel
;
declare @sql nvarchar(max), @columns nvarchar(max)
;
set @sql = CONVERT(nvarchar(max), (
    select number [data()]
    from master..spt_values
    where type='P' and number between 1 and (select MAX(level) from #tmp)
    order by 1
    for xml path('a')))
select @sql = stuff(replace(replace(@sql,'</a><a>','],['),'</a>',']'),1,3,'[')
select @sql = '
select ' + @sql + '
from #tmp
pivot (max(itemid) for level in (' + @sql + ')) v
order by ' + @sql
exec (@sql)

Резултатът

1       2       3       4
itemA   itemC   itemE   itemF
itemA   itemD   itemG   NULL
itemB   NULL    NULL    NULL



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SQL ревизиране на таблични данни в по-компактна форма

  2. Microsoft Access срещу SQL Server

  3. Вземете всичко след и преди определен знак в SQL Server

  4. Проблем с промяна на сортирането на база данни (SQL Server 2008)

  5. T-sql, отметки, клеймо за време