我正在使用分层数据并使用递归CTE列出这样的项目:
Eletronics
Televisions
Tube
LCD
Plasma
Portable Electronic
MP3 Players
Flash
CD Player
Two Way Radios
我的问题是:
如何按标题排序并尊重层次结构?
像这样:
Eletronics
Portable Electronic
CD Player
MP3 Players
Flash
Two Way Radios
Televisions
LCD
Plasma
Tube
韩国社交协会
答案 0 :(得分:3)
这是正确的CTE(仅适用于asc)
;WITH CTE AS
(
SELECT id, id_parent, name_product
,HierarchicalPath = CAST('\'+CAST(name_product AS VARCHAR(MAX)) AS VARCHAR(MAX))
FROM @tab where id_parent is null -- Starts with the first level
UNION ALL
SELECT t.id, t.id_parent, t.name_product
,HierarchicalPath = CAST(c.HierarchicalPath + '\'+CAST(t.name_product AS VARCHAR(MAX)) AS VARCHAR(MAX))
FROM @tab t INNER JOIN CTE C
ON t.id_parent = C.id
)
select * from cte order by HierarchicalPath
答案 1 :(得分:1)
这是我几乎完成了我想要的代码。 现在的问题是通过desc
订购declare @tab table(
id int identity(1,1)
,id_parent int
,name_product varchar(100)
)
insert into @tab
select null, 'Eletronics'
union all
select 1, 'Televisions'
union all
select 2, 'Tube'
union all
select 2, 'LCD'
union all
select 2, 'Plasma'
union all
select 1, 'Portable Electronic'
union all
select 6, 'MP3 Players'
union all
select 7, 'Flash'
union all
select 6, 'CD Player'
union all
select 6, 'Two Way Radios'
;WITH CTE (id,id_parent,name_product,LEVEL,SORTKEY)AS
(
SELECT id, id_parent, name_product, 1, CAST(name_product AS VARBINARY(MAX))
FROM @tab where id_parent is null -- Starts with the first level
UNION ALL
SELECT t.id, t.id_parent, t.name_product, C.LEVEL + 1, CAST(C.SORTKEY + CAST(t.name_product AS VARBINARY(MAX)) AS VARBINARY(MAX))
FROM @tab t INNER JOIN CTE C
ON t.id_parent = C.id
)
select * from cte order by SORTKEY
韩国社交协会
答案 2 :(得分:1)
基于@onaiggac的变体(你可以使用他的数据:-))
;WITH CTE (id, id_parent, name_product, LEVEL, SORTKEY) AS
(
SELECT id, id_parent, name_product, 1,
CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS VARBINARY(MAX))
FROM @tab where id_parent is null -- Starts with the first level
UNION ALL
SELECT t.id, t.id_parent, t.name_product, C.LEVEL + 1,
C.SORTKEY + CAST(ROW_NUMBER() OVER (ORDER BY t.name_product) AS VARBINARY(MAX))
FROM @tab t
INNER JOIN CTE C ON t.id_parent = C.id
)
SELECT id, id_parent, REPLICATE(' ', LEVEL - 1) + name_product, LEVEL, SORTKEY FROM CTE ORDER BY SORTKEY
这里的诀窍是使用
ROW_NUMBER() OVER (ORDER BY name_product)
做“内心”排序。与在@onaiggac中一样,它由二进制varbinary(max)
CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS VARBINARY(MAX))
然后以递归方式添加......
C.SORTKEY + CAST(ROW_NUMBER() OVER (ORDER BY t.name_product) AS VARBINARY(MAX))
请注意,ROW_NUMBER()
会返回bigint
...您可以将其投放到int
,然后再投放到VARBINARY(MAX)
,例如
CAST(CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS INT) AS VARBINARY(MAX))
如果你真的想...我认为除非你的树真的深,否则我认为没有必要。