4

我正在使用分层数据并使用递归 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

Tks

4

3 回答 3

4

这是正确的 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
于 2013-08-23T21:15:04.963 回答
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

Tks

于 2012-08-16T17:57:58.743 回答
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))

如果你真的想要......我认为除非你的树真的很深,否则没有必要。

于 2015-07-02T15:06:57.810 回答