How to get comma delimited CategoryIds recursively?

 ̄綄美尐妖づ 提交于 2019-12-11 00:16:25

问题


I have a table like this:

Name           CategoryId    ParentCategoryId
Footwear       93            0
Men Shoes      6             93
Female Shoes   7             93
Mobile         2             0
Smartphone     4             2

I need output like:

Name            Categories 
Footwear        93,0    
Men Shoes       6,93,0    
Female Shoes    7,93,0    
Mobile          2,0   
Smartphone      4,2,0       

Basically, I need to recursively get the category ids and make them into a comma delimited string. I am getting into SQL after 3 years now and I have no idea how to get this result. I have tried solutions from other SO questions but still no luck.


回答1:


You do this with recursive cte:

DECLARE @t TABLE
    (
      Name VARCHAR(100) ,
      CategoryId INT ,
      ParentCategoryId INT
    )
INSERT  INTO @t
VALUES  ( 'Footwear', 93, 0 ),
        ( 'Men Shoes', 6, 93 ),
        ( 'Female Shoes', 7, 93 ),
        ( 'Mobile', 2, 0 ),
        ( 'Smartphone', 4, 2 );

WITH    cte
          AS ( SELECT   * ,
                        CAST(CategoryId AS VARCHAR(100))  AS Categories
               FROM     @t
               WHERE    ParentCategoryId = 0
               UNION ALL
               SELECT   t.* ,
                        CAST(CAST(t.CategoryId AS VARCHAR(100)) + ','
                        + c.Categories AS VARCHAR(100))
               FROM     @t t
                        JOIN cte c ON c.CategoryId = t.ParentCategoryId
             )
    SELECT  *
    FROM    cte



回答2:


Try it with a recursive CTE:

DECLARE @tbl TABLE(Name VARCHAR(100),CategoryId INT,ParentCategoryId INT);
INSERT INTO @tbl VALUES
 ('Footwear',93,0)
,('Men Shoes',6,93)
,('Female Shoes',7,93)
,('Mobile',2,0)
,('Smartphone',4,2);

--based on this: http://stackoverflow.com/a/5522641/5089204
WITH tree (CategoryId, ParentCategoryId, level, Name, rn, IdList) as 
(
   SELECT CategoryId, ParentCategoryId, 0 as level, Name,
       convert(varchar(max),right(row_number() over (order by CategoryId),10)) AS rn,
       convert(varchar(max),ISNULL(CategoryId,0)) AS IdList
   FROM @tbl
   WHERE ParentCategoryId = 0

   UNION ALL

   SELECT c2.CategoryId, c2.ParentCategoryId, tree.level + 1, c2.Name,
       rn + '/' + convert(varchar(max),right(row_number() over (order by tree.CategoryId),10)),
       convert(varchar(max),c2.CategoryId) + ',' + IdList  
   FROM @tbl c2 
     INNER JOIN tree ON tree.CategoryId = c2.ParentCategoryId
)
SELECT *
FROM tree
order by RN

Part of the result:

1   Mobile        2
1/1 Smartphone    4,2
2   Footwear      93
2/1 Men Shoes     6,93
2/2 Female Shoes  7,93


来源:https://stackoverflow.com/questions/34332839/how-to-get-comma-delimited-categoryids-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!