如何将结果集形成如下表

时间:2018-03-13 14:37:22

标签: sql sql-server

表1包含某些数据集。我需要从表1中获得以下结果集

表1

Id  Desc          ParentId
1   Cloths            0
2   Mens              1
3   Womens            1
4   T-Shirt_M         2
5   Casual Shirts_M   2
6   T-Shirt_F         3
7   Education         8

如果我将参数传递给" Casual Shirts_M"我应该得到以下结果集。

结果集

Id  Desc          ParentId
1   Cloths            0
2   Mens              1
5   Casual Shirts_M   2

2 个答案:

答案 0 :(得分:5)

正如评论中所提到的,有很多递归公用表格表示例,这里是另一个

DECLARE @Desc NVARCHAR(50) = 'Casual Shirts_M'
;WITH cteX
AS
(   SELECT
        B.Id, B.[DESC], B.ParentId
    FROM
        Table1 b
    WHERE
        B.[Desc] = @Desc
    UNION ALL
    SELECT
        E.Id, E.[DESC], E.ParentId
    FROM
        Table1  E
    INNER JOIN
        cteX r ON e.Id = r.ParentId
)
SELECT * FROM cteX ORDER BY ID ASC
由@WhatsThePoint提供的

SQL-Fiddle

答案 1 :(得分:0)

问题来自使用递归CTE构建层次结构的概念:

 CREATE TABLE cloths 
  ( 
     id       INT, 
     descr    VARCHAR(100), 
     parentid INT 
  ); 


insert into cloths values (1,'Cloths',0);
insert into cloths values (2,'Mens',1);
insert into cloths values (3,'Womens',1);
insert into cloths values (4,'T-Shirt_M',2);
insert into cloths values (5,'Casual Shirts_M',2);
insert into cloths values (6,'T-Shirt_F',3);
insert into cloths values (7,'Education',8);


DECLARE @variety VARCHAR(100) = 'Casual Shirts_M'; 

WITH 
cte1 (id, descr, parentid) 
     AS (SELECT * 
         FROM   cloths 
         WHERE  descr = @variety 
         UNION ALL 
         SELECT c.id, 
                c.descr, 
                c.parentid 
         FROM   cloths c 
                INNER JOIN cte1 r 
                        ON c.id = r.parentid) 
SELECT * 
FROM   cte1 
ORDER  BY parentid ASC;