2

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.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
lbrahim
  • 3,710
  • 12
  • 57
  • 95

2 Answers2

3

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
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
  • Thanks. This worked for me. Can you also please tell me how I can eliminate the last Id which is always 0 from the comma delimited string column? – lbrahim Dec 17 '15 at 12:37
1

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
Shnugo
  • 66,100
  • 9
  • 53
  • 114